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 VB.NET Downloads
Dim success As Boolean = False
Dim stringCompare As New Chilkat.StringBuilder
' Assumes Chilkat is unlocked. See Global Unlock Sample.
' File format: {"messages":[<SNS envelope>, ...]}. Do not store untrusted files publicly.
Dim batch As New Chilkat.JsonObject
batch.Strict = True
success = batch.LoadFile("qa_data/aws/sns_notifications.json")
If (success <> True) Then
Debug.WriteLine("Could not parse notification envelopes.")
Exit Sub
End If
If (batch.JsonTypeOf("messages") <> 4) Then
Debug.WriteLine("Expected a messages array.")
Exit Sub
End If
Dim count As Integer = batch.SizeOfArray("messages")
If ((count < 1) Or (count > 100)) Then
Debug.WriteLine("Use 1 to 100 envelopes per verification batch.")
Exit Sub
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 New Chilkat.Hashtable
Dim envelope As New Chilkat.JsonObject
Dim now As New Chilkat.CkDateTime
success = now.SetFromCurrentSystemTime()
If (success <> True) Then
Debug.WriteLine("Could not read current time.")
Exit Sub
End If
Dim envelopeIndex As Integer = 0
While (envelopeIndex < count)
batch.I = envelopeIndex
success = batch.ObjectOf2("messages[i]",envelope)
If (success <> True) Then
Debug.WriteLine("Expected a JSON object envelope.")
Exit Sub
End If
Dim fieldNames As New Chilkat.Hashtable
Dim fieldIndex As Integer = 0
While (fieldIndex < envelope.Size)
Dim fieldName As String = envelope.NameAt(fieldIndex)
If (fieldNames.Contains(fieldName) = True) Then
Debug.WriteLine("Duplicate envelope field.")
Exit Sub
End If
success = fieldNames.AddStr(fieldName,"seen")
If (success <> True) Then
Debug.WriteLine("Could not track envelope fields.")
Exit Sub
End If
fieldIndex = fieldIndex + 1
End While
stringCompare.SetString(envelope.StringOf("Type"))
Dim stringMatch1 As Boolean = stringCompare.ContentsEqual("",True)
If ((envelope.JsonTypeOf("Type") <> 1) Or (stringMatch1 = True)) Then
Debug.WriteLine("Missing or invalid Type.")
Exit Sub
End If
stringCompare.SetString(envelope.StringOf("MessageId"))
Dim stringMatch2 As Boolean = stringCompare.ContentsEqual("",True)
If ((envelope.JsonTypeOf("MessageId") <> 1) Or (stringMatch2 = True)) Then
Debug.WriteLine("Missing or invalid MessageId.")
Exit Sub
End If
stringCompare.SetString(envelope.StringOf("Message"))
Dim stringMatch3 As Boolean = stringCompare.ContentsEqual("",True)
If ((envelope.JsonTypeOf("Message") <> 1) Or (stringMatch3 = True)) Then
Debug.WriteLine("Missing or invalid Message.")
Exit Sub
End If
stringCompare.SetString(envelope.StringOf("Timestamp"))
Dim stringMatch4 As Boolean = stringCompare.ContentsEqual("",True)
If ((envelope.JsonTypeOf("Timestamp") <> 1) Or (stringMatch4 = True)) Then
Debug.WriteLine("Missing or invalid Timestamp.")
Exit Sub
End If
stringCompare.SetString(envelope.StringOf("TopicArn"))
Dim stringMatch5 As Boolean = stringCompare.ContentsEqual("",True)
If ((envelope.JsonTypeOf("TopicArn") <> 1) Or (stringMatch5 = True)) Then
Debug.WriteLine("Missing or invalid TopicArn.")
Exit Sub
End If
stringCompare.SetString(envelope.StringOf("SignatureVersion"))
Dim stringMatch6 As Boolean = stringCompare.ContentsEqual("",True)
If ((envelope.JsonTypeOf("SignatureVersion") <> 1) Or (stringMatch6 = True)) Then
Debug.WriteLine("Missing or invalid SignatureVersion.")
Exit Sub
End If
stringCompare.SetString(envelope.StringOf("Signature"))
Dim stringMatch7 As Boolean = stringCompare.ContentsEqual("",True)
If ((envelope.JsonTypeOf("Signature") <> 1) Or (stringMatch7 = True)) Then
Debug.WriteLine("Missing or invalid Signature.")
Exit Sub
End If
stringCompare.SetString(envelope.StringOf("SigningCertURL"))
Dim stringMatch8 As Boolean = stringCompare.ContentsEqual("",True)
If ((envelope.JsonTypeOf("SigningCertURL") <> 1) Or (stringMatch8 = True)) Then
Debug.WriteLine("Missing or invalid SigningCertURL.")
Exit Sub
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
Debug.WriteLine("Unsupported SNS message type.")
Exit Sub
End If
stringCompare.SetString(envelope.StringOf("TopicArn"))
Dim stringMatch12 As Boolean = stringCompare.ContentsEqual(allowedTopic,True)
If (stringMatch12 <> True) Then
Debug.WriteLine("Unexpected SNS topic.")
Exit Sub
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
Debug.WriteLine("Unsupported delivery signature version.")
Exit Sub
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
Debug.WriteLine("Confirmation envelope is missing fields.")
Exit Sub
End If
End If
If (envelope.HasMember("Subject") = True) Then
If (envelope.JsonTypeOf("Subject") <> 1) Then
Debug.WriteLine("Subject must be a string when present.")
Exit Sub
End If
End If
Dim timestamp As New Chilkat.CkDateTime
success = timestamp.SetFromTimestamp(envelope.StringOf("Timestamp"))
If (success <> True) Then
Debug.WriteLine("Invalid notification timestamp.")
Exit Sub
End If
Dim ageSeconds As Integer = now.DiffSeconds(timestamp)
If ((ageSeconds < -300) Or (ageSeconds > 86400)) Then
Debug.WriteLine("Notification outside the configured 24-hour age / 5-minute clock-skew window.")
Exit Sub
End If
Dim certUrl As New Chilkat.StringBuilder
certUrl.Append(envelope.StringOf("SigningCertURL"))
Dim prefix As New Chilkat.StringBuilder
prefix.Append(certPrefix)
If ((certUrl.StartsWith(certPrefix,True) <> True) Or (certUrl.EndsWith(".pem",True) <> True) Or (certUrl.Length <= prefix.Length + 4)) Then
Debug.WriteLine("Untrusted signing-certificate URL.")
Exit Sub
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 New Chilkat.StringBuilder
filenameChars.Append("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_")
Dim charIndex As Integer = prefix.Length
While (charIndex < certUrl.Length - 4)
If (filenameChars.Contains(certUrl.GetRange(charIndex,1,False),True) <> True) Then
Debug.WriteLine("Invalid signing-certificate filename.")
Exit Sub
End If
charIndex = charIndex + 1
End While
Dim http As New Chilkat.Http
http.RequireSslCertVerify = True
http.FollowRedirects = False
http.ConnectTimeout = 20
http.ReadTimeout = 30
Dim maxCertBytes As UInt32 = 65536
http.MaxResponseSize = maxCertBytes
http.VerboseLogging = False
Dim certPem As String = http.QuickGetStr(certUrl.GetAsString())
If ((http.LastMethodSuccess <> True) Or (http.LastStatus <> 200)) Then
Debug.WriteLine("Could not retrieve the certificate securely from the pinned SNS endpoint.")
Exit Sub
End If
Dim signingCert As New Chilkat.Cert
success = signingCert.LoadPem(certPem)
If (success <> True) Then
Debug.WriteLine("Invalid signing certificate.")
Exit Sub
End If
Dim chain As New Chilkat.CertChain
success = signingCert.BuildCertChain(chain)
If (success <> True) Then
Debug.WriteLine("Could not build signing-certificate chain.")
Exit Sub
End If
If (chain.ReachesRoot <> True) Then
Debug.WriteLine("Incomplete signing-certificate chain; provision trusted intermediates.")
Exit Sub
End If
Dim roots As New Chilkat.TrustedRoots
roots.TrustSystemCaRoots = True
If (chain.IsRootTrusted(roots) <> True) Then
Debug.WriteLine("Untrusted signing-certificate root.")
Exit Sub
End If
success = chain.VerifyCertSignatures()
If (success <> True) Then
Debug.WriteLine("Invalid certificate-chain signatures.")
Exit Sub
End If
Dim certIndex As Integer = 0
Dim chainCert As New Chilkat.Cert
While (certIndex < chain.NumCerts)
success = chain.CertAt(certIndex,chainCert)
If (success <> True) Then
Debug.WriteLine("Could not read chain certificate.")
Exit Sub
End If
Dim validFrom As New Chilkat.CkDateTime
Dim validTo As New Chilkat.CkDateTime
success = validFrom.SetFromRfc822(chainCert.ValidFromStr)
If (success <> True) Then
Debug.WriteLine("Invalid certificate validity start.")
Exit Sub
End If
success = validTo.SetFromRfc822(chainCert.ValidToStr)
If (success <> True) Then
Debug.WriteLine("Invalid certificate validity end.")
Exit Sub
End If
If ((now.DiffSeconds(validFrom) < 0) Or (now.DiffSeconds(validTo) > 0)) Then
Debug.WriteLine("Certificate outside its validity period.")
Exit Sub
End If
certIndex = certIndex + 1
End While
Dim canonical As New Chilkat.StringBuilder
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 New Chilkat.PublicKey
success = signingCert.GetPublicKey(publicKey)
If (success <> True) Then
Debug.WriteLine("Could not extract signing public key.")
Exit Sub
End If
Dim rsa As New Chilkat.Rsa
rsa.Charset = "utf-8"
rsa.EncodingMode = "base64"
rsa.LittleEndian = False
success = rsa.UsePublicKey(publicKey)
If (success <> True) Then
Debug.WriteLine("Could not configure verification key.")
Exit Sub
End If
success = rsa.VerifyStringENC(canonical.GetAsString(),hashAlgorithm,envelope.StringOf("Signature"))
If (success <> True) Then
Debug.WriteLine("SNS delivery signature is invalid.")
Exit Sub
End If
' Use a JSON-encoded composite key to avoid ambiguous concatenation.
Dim identity As New Chilkat.JsonObject
success = identity.UpdateString("topic",allowedTopic)
If (success <> True) Then
Debug.WriteLine("Could not form duplicate key.")
Exit Sub
End If
success = identity.UpdateString("id",envelope.StringOf("MessageId"))
If (success <> True) Then
Debug.WriteLine("Could not form duplicate key.")
Exit Sub
End If
Dim duplicateKey As String = identity.Emit()
If (seenMessages.Contains(duplicateKey) = True) Then
Debug.WriteLine("Verified duplicate skipped: " & envelope.StringOf("MessageId"))
Else
success = seenMessages.AddStr(duplicateKey,"verified")
If (success <> True) Then
Debug.WriteLine("Could not track duplicate key.")
Exit Sub
End If
Debug.WriteLine("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
End While
Debug.WriteLine("All envelopes verified; duplicate detection was limited to this batch.")