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

B4X
Dim success As Boolean = False

Dim stringCompare As ChilkatStringBuilder
stringCompare.Initialize
'  Assumes Chilkat is unlocked. See Global Unlock Sample.
'  File format: {"messages":[<SNS envelope>, ...]}. Do not store untrusted files publicly.

Dim batch As ChilkatJsonObject
batch.Initialize
batch.Strict = True
success = batch.LoadFile("qa_data/aws/sns_notifications.json")
If success <> True Then
    Log("Could not parse notification envelopes.")
    Return
End If

If batch.JsonTypeOf("messages") <> 4 Then
    Log("Expected a messages array.")
    Return
End If

Dim count As Int = batch.SizeOfArray("messages")
If (count < 1) Or (count > 100) Then
    Log("Use 1 to 100 envelopes per verification batch.")
    Return
End If

Dim allowedTopic As String = "arn:aws:sns:us-west-2:123456789012:chilkat-standard-example"
Dim certPrefix As String = "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-"
'  Pin the expected topic and matching regional SNS host in application configuration.
Dim seenMessages As ChilkatHashtable
seenMessages.Initialize
Dim envelope As ChilkatJsonObject
envelope.Initialize
Dim now As ChilkatDateTime
now.Initialize
success = now.SetFromCurrentSystemTime
If success <> True Then
    Log("Could not read current time.")
    Return
End If

Dim envelopeIndex As Int = 0
Do While (envelopeIndex < count)
    batch.I = envelopeIndex
    success = batch.ObjectOf2("messages[i]", envelope)
    If success <> True Then
        Log("Expected a JSON object envelope.")
        Return
    End If

    Dim fieldNames As ChilkatHashtable
    fieldNames.Initialize
    Dim fieldIndex As Int = 0
    Do While (fieldIndex < envelope.Size)
        Dim fieldName As String = envelope.NameAt(fieldIndex)
        If fieldNames.Contains(fieldName) = True Then
            Log("Duplicate envelope field.")
            Return
        End If

        success = fieldNames.AddStr(fieldName, "seen")
        If success <> True Then
            Log("Could not track envelope fields.")
            Return
        End If

        fieldIndex = fieldIndex + 1
    Loop
    stringCompare.SetString(envelope.StringOf("Type"))
    Dim stringMatch1 As Boolean = stringCompare.ContentsEqual("", True)
    If (envelope.JsonTypeOf("Type") <> 1) Or (stringMatch1 = True) Then
        Log("Missing or invalid Type.")
        Return
    End If

    stringCompare.SetString(envelope.StringOf("MessageId"))
    Dim stringMatch2 As Boolean = stringCompare.ContentsEqual("", True)
    If (envelope.JsonTypeOf("MessageId") <> 1) Or (stringMatch2 = True) Then
        Log("Missing or invalid MessageId.")
        Return
    End If

    stringCompare.SetString(envelope.StringOf("Message"))
    Dim stringMatch3 As Boolean = stringCompare.ContentsEqual("", True)
    If (envelope.JsonTypeOf("Message") <> 1) Or (stringMatch3 = True) Then
        Log("Missing or invalid Message.")
        Return
    End If

    stringCompare.SetString(envelope.StringOf("Timestamp"))
    Dim stringMatch4 As Boolean = stringCompare.ContentsEqual("", True)
    If (envelope.JsonTypeOf("Timestamp") <> 1) Or (stringMatch4 = True) Then
        Log("Missing or invalid Timestamp.")
        Return
    End If

    stringCompare.SetString(envelope.StringOf("TopicArn"))
    Dim stringMatch5 As Boolean = stringCompare.ContentsEqual("", True)
    If (envelope.JsonTypeOf("TopicArn") <> 1) Or (stringMatch5 = True) Then
        Log("Missing or invalid TopicArn.")
        Return
    End If

    stringCompare.SetString(envelope.StringOf("SignatureVersion"))
    Dim stringMatch6 As Boolean = stringCompare.ContentsEqual("", True)
    If (envelope.JsonTypeOf("SignatureVersion") <> 1) Or (stringMatch6 = True) Then
        Log("Missing or invalid SignatureVersion.")
        Return
    End If

    stringCompare.SetString(envelope.StringOf("Signature"))
    Dim stringMatch7 As Boolean = stringCompare.ContentsEqual("", True)
    If (envelope.JsonTypeOf("Signature") <> 1) Or (stringMatch7 = True) Then
        Log("Missing or invalid Signature.")
        Return
    End If

    stringCompare.SetString(envelope.StringOf("SigningCertURL"))
    Dim stringMatch8 As Boolean = stringCompare.ContentsEqual("", True)
    If (envelope.JsonTypeOf("SigningCertURL") <> 1) Or (stringMatch8 = True) Then
        Log("Missing or invalid SigningCertURL.")
        Return
    End If

    Dim messageType As String = envelope.StringOf("Type")
    stringCompare.SetString(messageType)
    Dim stringMatch9 As Boolean = stringCompare.ContentsEqual("Notification", True)
    stringCompare.SetString(messageType)
    Dim stringMatch10 As Boolean = stringCompare.ContentsEqual("SubscriptionConfirmation", True)
    stringCompare.SetString(messageType)
    Dim stringMatch11 As Boolean = stringCompare.ContentsEqual("UnsubscribeConfirmation", True)
    If (stringMatch9 <> True) And (stringMatch10 <> True) And (stringMatch11 <> True) Then
        Log("Unsupported SNS message type.")
        Return
    End If

    stringCompare.SetString(envelope.StringOf("TopicArn"))
    Dim stringMatch12 As Boolean = stringCompare.ContentsEqual(allowedTopic, True)
    If stringMatch12 <> True Then
        Log("Unexpected SNS topic.")
        Return
    End If

    Dim signatureVersion As String = envelope.StringOf("SignatureVersion")
    stringCompare.SetString(signatureVersion)
    Dim stringMatch13 As Boolean = stringCompare.ContentsEqual("1", True)
    stringCompare.SetString(signatureVersion)
    Dim stringMatch14 As Boolean = stringCompare.ContentsEqual("2", True)
    If (stringMatch13 <> True) And (stringMatch14 <> True) Then
        Log("Unsupported delivery signature version.")
        Return
    End If

    Dim hashAlgorithm As String = "sha256"
    stringCompare.SetString(signatureVersion)
    Dim stringMatch15 As Boolean = stringCompare.ContentsEqual("1", True)
    If stringMatch15 = True Then
        hashAlgorithm = "sha1"
    End If

    stringCompare.SetString(messageType)
    Dim stringMatch16 As Boolean = stringCompare.ContentsEqual("Notification", True)
    If stringMatch16 <> True Then
        stringCompare.SetString(envelope.StringOf("SubscribeURL"))
        Dim stringMatch17 As Boolean = stringCompare.ContentsEqual("", True)
        stringCompare.SetString(envelope.StringOf("Token"))
        Dim stringMatch18 As Boolean = stringCompare.ContentsEqual("", True)
        If (envelope.JsonTypeOf("SubscribeURL") <> 1) Or (stringMatch17 = True) Or (envelope.JsonTypeOf("Token") <> 1) Or (stringMatch18 = True) Then
            Log("Confirmation envelope is missing fields.")
            Return
        End If

    End If

    If envelope.HasMember("Subject") = True Then
        If envelope.JsonTypeOf("Subject") <> 1 Then
            Log("Subject must be a string when present.")
            Return
        End If

    End If

    Dim timestamp As ChilkatDateTime
    timestamp.Initialize
    success = timestamp.SetFromTimestamp(envelope.StringOf("Timestamp"))
    If success <> True Then
        Log("Invalid notification timestamp.")
        Return
    End If

    Dim ageSeconds As Int = now.DiffSeconds(timestamp)
    If (ageSeconds < -300) Or (ageSeconds > 86400) Then
        Log("Notification outside the configured 24-hour age / 5-minute clock-skew window.")
        Return
    End If

    Dim certUrl As ChilkatStringBuilder
    certUrl.Initialize
    certUrl.Append(envelope.StringOf("SigningCertURL"))
    Dim prefix As ChilkatStringBuilder
    prefix.Initialize
    prefix.Append(certPrefix)
    If (certUrl.StartsWith(certPrefix, True) <> True) Or (certUrl.EndsWith(".pem", True) <> True) Or (certUrl.Length <= prefix.Length + 4) Then
        Log("Untrusted signing-certificate URL.")
        Return
    End If

    '  Only a flat SNS certificate filename is allowed: no query, fragment, escapes,
    '  userinfo, alternate port, path traversal, or redirect destination.
    Dim filenameChars As ChilkatStringBuilder
    filenameChars.Initialize
    filenameChars.Append("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_")
    Dim charIndex As Int = prefix.Length
    Do While (charIndex < certUrl.Length - 4)
        If filenameChars.Contains(certUrl.GetRange(charIndex, 1, False), True) <> True Then
            Log("Invalid signing-certificate filename.")
            Return
        End If

        charIndex = charIndex + 1
    Loop
    Dim http As ChilkatHttp
    http.Initialize("http")
    http.RequireSslCertVerify = True
    http.FollowRedirects = False
    http.ConnectTimeout = 20
    http.ReadTimeout = 30
    Dim maxCertBytes As Long = 65536
    http.MaxResponseSize = maxCertBytes
    http.VerboseLogging = False
    Dim certPem As String = http.QuickGetStr(certUrl.GetAsString)
    If (http.LastMethodSuccess <> True) Or (http.LastStatus <> 200) Then
        Log("Could not retrieve the certificate securely from the pinned SNS endpoint.")
        Return
    End If

    Dim signingCert As ChilkatCert
    signingCert.Initialize("signingCert")
    success = signingCert.LoadPem(certPem)
    If success <> True Then
        Log("Invalid signing certificate.")
        Return
    End If

    Dim chain As ChilkatCertChain
    chain.Initialize
    success = signingCert.BuildCertChain(chain)
    If success <> True Then
        Log("Could not build signing-certificate chain.")
        Return
    End If

    If chain.ReachesRoot <> True Then
        Log("Incomplete signing-certificate chain; provision trusted intermediates.")
        Return
    End If

    Dim roots As ChilkatTrustedRoots
    roots.Initialize("roots")
    roots.TrustSystemCaRoots = True
    If chain.IsRootTrusted(roots) <> True Then
        Log("Untrusted signing-certificate root.")
        Return
    End If

    success = chain.VerifyCertSignatures
    If success <> True Then
        Log("Invalid certificate-chain signatures.")
        Return
    End If

    Dim certIndex As Int = 0
    Dim chainCert As ChilkatCert
    chainCert.Initialize("chainCert")
    Do While (certIndex < chain.NumCerts)
        success = chain.CertAt(certIndex, chainCert)
        If success <> True Then
            Log("Could not read chain certificate.")
            Return
        End If

        Dim validFrom As ChilkatDateTime
        validFrom.Initialize
        Dim validTo As ChilkatDateTime
        validTo.Initialize
        success = validFrom.SetFromRfc822(chainCert.ValidFromStr)
        If success <> True Then
            Log("Invalid certificate validity start.")
            Return
        End If

        success = validTo.SetFromRfc822(chainCert.ValidToStr)
        If success <> True Then
            Log("Invalid certificate validity end.")
            Return
        End If

        If (now.DiffSeconds(validFrom) < 0) Or (now.DiffSeconds(validTo) > 0) Then
            Log("Certificate outside its validity period.")
            Return
        End If

        certIndex = certIndex + 1
    Loop
    Dim canonical As ChilkatStringBuilder
    canonical.Initialize
    canonical.AppendLine("Message", False)
    canonical.AppendLine(envelope.StringOf("Message"), False)
    canonical.AppendLine("MessageId", False)
    canonical.AppendLine(envelope.StringOf("MessageId"), False)
    stringCompare.SetString(messageType)
    Dim stringMatch19 As Boolean = stringCompare.ContentsEqual("Notification", True)
    If stringMatch19 = True Then
        If envelope.HasMember("Subject") = True Then
            canonical.AppendLine("Subject", False)
            canonical.AppendLine(envelope.StringOf("Subject"), False)
        End If

    Else
        canonical.AppendLine("SubscribeURL", False)
        canonical.AppendLine(envelope.StringOf("SubscribeURL"), False)
    End If

    canonical.AppendLine("Timestamp", False)
    canonical.AppendLine(envelope.StringOf("Timestamp"), False)
    stringCompare.SetString(messageType)
    Dim stringMatch20 As Boolean = stringCompare.ContentsEqual("Notification", True)
    If stringMatch20 <> True Then
        canonical.AppendLine("Token", False)
        canonical.AppendLine(envelope.StringOf("Token"), False)
    End If

    canonical.AppendLine("TopicArn", False)
    canonical.AppendLine(envelope.StringOf("TopicArn"), False)
    canonical.AppendLine("Type", False)
    canonical.AppendLine(envelope.StringOf("Type"), False)
    Dim publicKey As ChilkatPublicKey
    publicKey.Initialize
    success = signingCert.GetPublicKey(publicKey)
    If success <> True Then
        Log("Could not extract signing public key.")
        Return
    End If

    Dim rsa As ChilkatRsa
    rsa.Initialize
    rsa.Charset = "utf-8"
    rsa.EncodingMode = "base64"
    rsa.LittleEndian = False
    success = rsa.UsePublicKey(publicKey)
    If success <> True Then
        Log("Could not configure verification key.")
        Return
    End If

    success = rsa.VerifyStringENC(canonical.GetAsString, hashAlgorithm, envelope.StringOf("Signature"))
    If success <> True Then
        Log("SNS delivery signature is invalid.")
        Return
    End If

    '  Use a JSON-encoded composite key to avoid ambiguous concatenation.
    Dim identity As ChilkatJsonObject
    identity.Initialize
    success = identity.UpdateString("topic", allowedTopic)
    If success <> True Then
        Log("Could not form duplicate key.")
        Return
    End If

    success = identity.UpdateString("id", envelope.StringOf("MessageId"))
    If success <> True Then
        Log("Could not form duplicate key.")
        Return
    End If

    Dim duplicateKey As String = identity.Emit
    If seenMessages.Contains(duplicateKey) = True Then
        Log("Verified duplicate skipped: " & envelope.StringOf("MessageId"))
    Else
        success = seenMessages.AddStr(duplicateKey, "verified")
        If success <> True Then
            Log("Could not track duplicate key.")
            Return
        End If

        Log("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.
    End If

    envelopeIndex = envelopeIndex + 1
Loop
Log("All envelopes verified; duplicate detection was limited to this batch.")