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

Lua
local chilkat = require("chilkat")

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

local batch = chilkat.JsonObject.new()
batch.strict = true
local success = batch:load_file("qa_data/aws/sns_notifications.json")
if not success then
    print("Could not parse notification envelopes.")
    return
end

if batch:json_type_of("messages") ~= 4 then
    print("Expected a messages array.")
    return
end

local count = batch:size_of_array("messages")
if (count < 1) or (count > 100) then
    print("Use 1 to 100 envelopes per verification batch.")
    return
end

local allowedTopic = "arn:aws:sns:us-west-2:123456789012:chilkat-standard-example"
local certPrefix = "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-"
-- Pin the expected topic and matching regional SNS host in application configuration.
local seenMessages = chilkat.Hashtable.new()
local envelope = chilkat.JsonObject.new()
local now = chilkat.DateTime.new()
success = now:set_from_current_system_time()
if not success then
    print("Could not read current time.")
    return
end

local envelopeIndex = 0
while envelopeIndex < count do
    batch.i = envelopeIndex
    success = batch:object_of2("messages[i]", envelope)
    if not success then
        print("Expected a JSON object envelope.")
        return
    end

    local fieldNames = chilkat.Hashtable.new()
    local fieldIndex = 0
    while fieldIndex < envelope.size do
        local fieldName = envelope:name_at(fieldIndex)
        if fieldNames:contains(fieldName) then
            print("Duplicate envelope field.")
            return
        end

        success = fieldNames:add_str(fieldName, "seen")
        if not success then
            print("Could not track envelope fields.")
            return
        end

        fieldIndex = fieldIndex + 1
    end

    stringCompare:set_string(envelope:string_of("Type"))
    local stringMatch1 = stringCompare:contents_equal("", true)
    if (envelope:json_type_of("Type") ~= 1) or (stringMatch1) then
        print("Missing or invalid Type.")
        return
    end

    stringCompare:set_string(envelope:string_of("MessageId"))
    local stringMatch2 = stringCompare:contents_equal("", true)
    if (envelope:json_type_of("MessageId") ~= 1) or (stringMatch2) then
        print("Missing or invalid MessageId.")
        return
    end

    stringCompare:set_string(envelope:string_of("Message"))
    local stringMatch3 = stringCompare:contents_equal("", true)
    if (envelope:json_type_of("Message") ~= 1) or (stringMatch3) then
        print("Missing or invalid Message.")
        return
    end

    stringCompare:set_string(envelope:string_of("Timestamp"))
    local stringMatch4 = stringCompare:contents_equal("", true)
    if (envelope:json_type_of("Timestamp") ~= 1) or (stringMatch4) then
        print("Missing or invalid Timestamp.")
        return
    end

    stringCompare:set_string(envelope:string_of("TopicArn"))
    local stringMatch5 = stringCompare:contents_equal("", true)
    if (envelope:json_type_of("TopicArn") ~= 1) or (stringMatch5) then
        print("Missing or invalid TopicArn.")
        return
    end

    stringCompare:set_string(envelope:string_of("SignatureVersion"))
    local stringMatch6 = stringCompare:contents_equal("", true)
    if (envelope:json_type_of("SignatureVersion") ~= 1) or (stringMatch6) then
        print("Missing or invalid SignatureVersion.")
        return
    end

    stringCompare:set_string(envelope:string_of("Signature"))
    local stringMatch7 = stringCompare:contents_equal("", true)
    if (envelope:json_type_of("Signature") ~= 1) or (stringMatch7) then
        print("Missing or invalid Signature.")
        return
    end

    stringCompare:set_string(envelope:string_of("SigningCertURL"))
    local stringMatch8 = stringCompare:contents_equal("", true)
    if (envelope:json_type_of("SigningCertURL") ~= 1) or (stringMatch8) then
        print("Missing or invalid SigningCertURL.")
        return
    end

    local messageType = envelope:string_of("Type")
    stringCompare:set_string(messageType)
    local stringMatch9 = stringCompare:contents_equal("Notification", true)
    stringCompare:set_string(messageType)
    local stringMatch10 = stringCompare:contents_equal("SubscriptionConfirmation", true)
    stringCompare:set_string(messageType)
    local stringMatch11 = stringCompare:contents_equal("UnsubscribeConfirmation", true)
    if (not stringMatch9) and ((not stringMatch10) and (not stringMatch11)) then
        print("Unsupported SNS message type.")
        return
    end

    stringCompare:set_string(envelope:string_of("TopicArn"))
    local stringMatch12 = stringCompare:contents_equal(allowedTopic, true)
    if not stringMatch12 then
        print("Unexpected SNS topic.")
        return
    end

    local signatureVersion = envelope:string_of("SignatureVersion")
    stringCompare:set_string(signatureVersion)
    local stringMatch13 = stringCompare:contents_equal("1", true)
    stringCompare:set_string(signatureVersion)
    local stringMatch14 = stringCompare:contents_equal("2", true)
    if (not stringMatch13) and (not stringMatch14) then
        print("Unsupported delivery signature version.")
        return
    end

    local hashAlgorithm = "sha256"
    stringCompare:set_string(signatureVersion)
    local stringMatch15 = stringCompare:contents_equal("1", true)
    if stringMatch15 then
        hashAlgorithm = "sha1"
    end

    stringCompare:set_string(messageType)
    local stringMatch16 = stringCompare:contents_equal("Notification", true)
    if not stringMatch16 then
        stringCompare:set_string(envelope:string_of("SubscribeURL"))
        local stringMatch17 = stringCompare:contents_equal("", true)
        stringCompare:set_string(envelope:string_of("Token"))
        local stringMatch18 = stringCompare:contents_equal("", true)
        if (envelope:json_type_of("SubscribeURL") ~= 1) or ((stringMatch17) or ((envelope:json_type_of("Token") ~= 1) or (stringMatch18))) then
            print("Confirmation envelope is missing fields.")
            return
        end
    end

    if envelope:has_member("Subject") then
        if envelope:json_type_of("Subject") ~= 1 then
            print("Subject must be a string when present.")
            return
        end
    end

    local timestamp = chilkat.DateTime.new()
    success = timestamp:set_from_timestamp(envelope:string_of("Timestamp"))
    if not success then
        print("Invalid notification timestamp.")
        return
    end

    local ageSeconds = now:diff_seconds(timestamp)
    if (ageSeconds < (-300)) or (ageSeconds > 86400) then
        print("Notification outside the configured 24-hour age / 5-minute clock-skew window.")
        return
    end

    local certUrl = chilkat.StringBuilder.new()
    certUrl:append(envelope:string_of("SigningCertURL"))
    local prefix = chilkat.StringBuilder.new()
    prefix:append(certPrefix)
    if (not certUrl:starts_with(certPrefix, true)) or ((not certUrl:ends_with(".pem", true)) or (certUrl.length <= prefix.length + 4)) then
        print("Untrusted signing-certificate URL.")
        return
    end

    -- Only a flat SNS certificate filename is allowed: no query, fragment, escapes,
    -- userinfo, alternate port, path traversal, or redirect destination.
    local filenameChars = chilkat.StringBuilder.new()
    filenameChars:append("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_")
    local charIndex = prefix.length
    while charIndex < certUrl.length - 4 do
        if not filenameChars:contains(certUrl:get_range(charIndex, 1, false), true) then
            print("Invalid signing-certificate filename.")
            return
        end

        charIndex = charIndex + 1
    end

    local http = chilkat.Http.new()
    http.require_ssl_cert_verify = true
    http.follow_redirects = false
    http.connect_timeout = 20
    http.read_timeout = 30
    local maxCertBytes = 65536
    http.max_response_size = maxCertBytes
    http.verbose_logging = false
    local certPem = http:quick_get_str(certUrl:get_as_string())
    if (not http.last_method_success) or (http.last_status ~= 200) then
        print("Could not retrieve the certificate securely from the pinned SNS endpoint.")
        return
    end

    local signingCert = chilkat.Cert.new()
    success = signingCert:load_pem(certPem)
    if not success then
        print("Invalid signing certificate.")
        return
    end

    local chain = chilkat.CertChain.new()
    success = signingCert:build_cert_chain(chain)
    if not success then
        print("Could not build signing-certificate chain.")
        return
    end

    if not chain.reaches_root then
        print("Incomplete signing-certificate chain; provision trusted intermediates.")
        return
    end

    local roots = chilkat.TrustedRoots.new()
    roots.trust_system_ca_roots = true
    if not chain:is_root_trusted(roots) then
        print("Untrusted signing-certificate root.")
        return
    end

    success = chain:verify_cert_signatures()
    if not success then
        print("Invalid certificate-chain signatures.")
        return
    end

    local certIndex = 0
    local chainCert = chilkat.Cert.new()
    while certIndex < chain.num_certs do
        success = chain:cert_at(certIndex, chainCert)
        if not success then
            print("Could not read chain certificate.")
            return
        end

        local validFrom = chilkat.DateTime.new()
        local validTo = chilkat.DateTime.new()
        success = validFrom:set_from_rfc822(chainCert.valid_from_str)
        if not success then
            print("Invalid certificate validity start.")
            return
        end

        success = validTo:set_from_rfc822(chainCert.valid_to_str)
        if not success then
            print("Invalid certificate validity end.")
            return
        end

        if (now:diff_seconds(validFrom) < 0) or (now:diff_seconds(validTo) > 0) then
            print("Certificate outside its validity period.")
            return
        end

        certIndex = certIndex + 1
    end

    local canonical = chilkat.StringBuilder.new()
    canonical:append_line("Message", false)
    canonical:append_line(envelope:string_of("Message"), false)
    canonical:append_line("MessageId", false)
    canonical:append_line(envelope:string_of("MessageId"), false)
    stringCompare:set_string(messageType)
    local stringMatch19 = stringCompare:contents_equal("Notification", true)
    if stringMatch19 then
        if envelope:has_member("Subject") then
            canonical:append_line("Subject", false)
            canonical:append_line(envelope:string_of("Subject"), false)
        end
    else
        canonical:append_line("SubscribeURL", false)
        canonical:append_line(envelope:string_of("SubscribeURL"), false)
    end

    canonical:append_line("Timestamp", false)
    canonical:append_line(envelope:string_of("Timestamp"), false)
    stringCompare:set_string(messageType)
    local stringMatch20 = stringCompare:contents_equal("Notification", true)
    if not stringMatch20 then
        canonical:append_line("Token", false)
        canonical:append_line(envelope:string_of("Token"), false)
    end

    canonical:append_line("TopicArn", false)
    canonical:append_line(envelope:string_of("TopicArn"), false)
    canonical:append_line("Type", false)
    canonical:append_line(envelope:string_of("Type"), false)
    local publicKey = chilkat.PublicKey.new()
    success = signingCert:get_public_key(publicKey)
    if not success then
        print("Could not extract signing public key.")
        return
    end

    local rsa = chilkat.Rsa.new()
    rsa.charset = "utf-8"
    rsa.encoding_mode = "base64"
    rsa.little_endian = false
    success = rsa:use_public_key(publicKey)
    if not success then
        print("Could not configure verification key.")
        return
    end

    success = rsa:verify_string_enc(canonical:get_as_string(), hashAlgorithm, envelope:string_of("Signature"))
    if not success then
        print("SNS delivery signature is invalid.")
        return
    end

    -- Use a JSON-encoded composite key to avoid ambiguous concatenation.
    local identity = chilkat.JsonObject.new()
    success = identity:update_string("topic", allowedTopic)
    if not success then
        print("Could not form duplicate key.")
        return
    end

    success = identity:update_string("id", envelope:string_of("MessageId"))
    if not success then
        print("Could not form duplicate key.")
        return
    end

    local duplicateKey = identity:emit()
    if seenMessages:contains(duplicateKey) then
        print("Verified duplicate skipped: " .. envelope:string_of("MessageId"))
    else
        success = seenMessages:add_str(duplicateKey, "verified")
        if not success then
            print("Could not track duplicate key.")
            return
        end

        print("Verified " .. messageType .. " / " .. envelope:string_of("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

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