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

Swift

func chilkatTest() {
    var success: Bool = false

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

    let batch = CkoJsonObject()!
    batch.strict = true
    success = batch.loadFile(path: "qa_data/aws/sns_notifications.json")
    if success != true {
        print("Could not parse notification envelopes.")
        return
    }

    if batch.jsonType(of: "messages").intValue != 4 {
        print("Expected a messages array.")
        return
    }

    var count: Int = batch.size(ofArray: "messages").intValue
    if (count < 1) || (count > 100) {
        print("Use 1 to 100 envelopes per verification batch.")
        return
    }

    var allowedTopic: String? = "arn:aws:sns:us-west-2:123456789012:chilkat-standard-example"
    var certPrefix: String? = "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-"
    //  Pin the expected topic and matching regional SNS host in application configuration.
    let seenMessages = CkoHashtable()!
    let envelope = CkoJsonObject()!
    let now = CkoDateTime()!
    success = now.setFromCurrentSystemTime()
    if success != true {
        print("Could not read current time.")
        return
    }

    var envelopeIndex: Int = 0
    while (envelopeIndex < count) {
        batch.i = envelopeIndex
        success = batch.objectOf2(jsonPath: "messages[i]", jsonObj: envelope)
        if success != true {
            print("Expected a JSON object envelope.")
            return
        }

        let fieldNames = CkoHashtable()!
        var fieldIndex: Int = 0
        while (fieldIndex < envelope.size.intValue) {
            var fieldName: String? = envelope.name(at: fieldIndex)
            if fieldNames.contains(key: fieldName) == true {
                print("Duplicate envelope field.")
                return
            }

            success = fieldNames.addStr(key: fieldName, value: "seen")
            if success != true {
                print("Could not track envelope fields.")
                return
            }

            fieldIndex = fieldIndex + 1
        }

        stringCompare.setString(value: envelope.string(of: "Type"))
        var stringMatch1: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
        if (envelope.jsonType(of: "Type").intValue != 1) || (stringMatch1 == true) {
            print("Missing or invalid Type.")
            return
        }

        stringCompare.setString(value: envelope.string(of: "MessageId"))
        var stringMatch2: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
        if (envelope.jsonType(of: "MessageId").intValue != 1) || (stringMatch2 == true) {
            print("Missing or invalid MessageId.")
            return
        }

        stringCompare.setString(value: envelope.string(of: "Message"))
        var stringMatch3: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
        if (envelope.jsonType(of: "Message").intValue != 1) || (stringMatch3 == true) {
            print("Missing or invalid Message.")
            return
        }

        stringCompare.setString(value: envelope.string(of: "Timestamp"))
        var stringMatch4: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
        if (envelope.jsonType(of: "Timestamp").intValue != 1) || (stringMatch4 == true) {
            print("Missing or invalid Timestamp.")
            return
        }

        stringCompare.setString(value: envelope.string(of: "TopicArn"))
        var stringMatch5: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
        if (envelope.jsonType(of: "TopicArn").intValue != 1) || (stringMatch5 == true) {
            print("Missing or invalid TopicArn.")
            return
        }

        stringCompare.setString(value: envelope.string(of: "SignatureVersion"))
        var stringMatch6: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
        if (envelope.jsonType(of: "SignatureVersion").intValue != 1) || (stringMatch6 == true) {
            print("Missing or invalid SignatureVersion.")
            return
        }

        stringCompare.setString(value: envelope.string(of: "Signature"))
        var stringMatch7: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
        if (envelope.jsonType(of: "Signature").intValue != 1) || (stringMatch7 == true) {
            print("Missing or invalid Signature.")
            return
        }

        stringCompare.setString(value: envelope.string(of: "SigningCertURL"))
        var stringMatch8: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
        if (envelope.jsonType(of: "SigningCertURL").intValue != 1) || (stringMatch8 == true) {
            print("Missing or invalid SigningCertURL.")
            return
        }

        var messageType: String? = envelope.string(of: "Type")
        stringCompare.setString(value: messageType)
        var stringMatch9: Bool = stringCompare.contentsEqual(str: "Notification", caseSensitive: true)
        stringCompare.setString(value: messageType)
        var stringMatch10: Bool = stringCompare.contentsEqual(str: "SubscriptionConfirmation", caseSensitive: true)
        stringCompare.setString(value: messageType)
        var stringMatch11: Bool = stringCompare.contentsEqual(str: "UnsubscribeConfirmation", caseSensitive: true)
        if (stringMatch9 != true) && (stringMatch10 != true) && (stringMatch11 != true) {
            print("Unsupported SNS message type.")
            return
        }

        stringCompare.setString(value: envelope.string(of: "TopicArn"))
        var stringMatch12: Bool = stringCompare.contentsEqual(str: allowedTopic, caseSensitive: true)
        if stringMatch12 != true {
            print("Unexpected SNS topic.")
            return
        }

        var signatureVersion: String? = envelope.string(of: "SignatureVersion")
        stringCompare.setString(value: signatureVersion)
        var stringMatch13: Bool = stringCompare.contentsEqual(str: "1", caseSensitive: true)
        stringCompare.setString(value: signatureVersion)
        var stringMatch14: Bool = stringCompare.contentsEqual(str: "2", caseSensitive: true)
        if (stringMatch13 != true) && (stringMatch14 != true) {
            print("Unsupported delivery signature version.")
            return
        }

        var hashAlgorithm: String? = "sha256"
        stringCompare.setString(value: signatureVersion)
        var stringMatch15: Bool = stringCompare.contentsEqual(str: "1", caseSensitive: true)
        if stringMatch15 == true {
            hashAlgorithm = "sha1"
        }

        stringCompare.setString(value: messageType)
        var stringMatch16: Bool = stringCompare.contentsEqual(str: "Notification", caseSensitive: true)
        if stringMatch16 != true {
            stringCompare.setString(value: envelope.string(of: "SubscribeURL"))
            var stringMatch17: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
            stringCompare.setString(value: envelope.string(of: "Token"))
            var stringMatch18: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
            if (envelope.jsonType(of: "SubscribeURL").intValue != 1) || (stringMatch17 == true) || (envelope.jsonType(of: "Token").intValue != 1) || (stringMatch18 == true) {
                print("Confirmation envelope is missing fields.")
                return
            }

        }

        if envelope.hasMember(jsonPath: "Subject") == true {
            if envelope.jsonType(of: "Subject").intValue != 1 {
                print("Subject must be a string when present.")
                return
            }

        }

        let timestamp = CkoDateTime()!
        success = timestamp.set(fromTimestamp: envelope.string(of: "Timestamp"))
        if success != true {
            print("Invalid notification timestamp.")
            return
        }

        var ageSeconds: Int = now.diffSeconds(dateTimeArg: timestamp).intValue
        if (ageSeconds < -300) || (ageSeconds > 86400) {
            print("Notification outside the configured 24-hour age / 5-minute clock-skew window.")
            return
        }

        let certUrl = CkoStringBuilder()!
        certUrl.append(value: envelope.string(of: "SigningCertURL"))
        let prefix = CkoStringBuilder()!
        prefix.append(value: certPrefix)
        if (certUrl.starts(with: certPrefix, caseSensitive: true) != true) || (certUrl.ends(with: ".pem", caseSensitive: true) != true) || (certUrl.length.intValue <= prefix.length.intValue + 4) {
            print("Untrusted signing-certificate URL.")
            return
        }

        //  Only a flat SNS certificate filename is allowed: no query, fragment, escapes,
        //  userinfo, alternate port, path traversal, or redirect destination.
        let filenameChars = CkoStringBuilder()!
        filenameChars.append(value: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_")
        var charIndex: Int = prefix.length.intValue
        while (charIndex < certUrl.length.intValue - 4) {
            if filenameChars.contains(str: certUrl.getRange(startIndex: charIndex, numChars: 1, removeFlag: false), caseSensitive: true) != true {
                print("Invalid signing-certificate filename.")
                return
            }

            charIndex = charIndex + 1
        }

        let http = CkoHttp()!
        http.requireSslCertVerify = true
        http.followRedirects = false
        http.connectTimeout = 20
        http.readTimeout = 30
        var maxCertBytes: UInt32 = 65536
        http.maxResponseSize = maxCertBytes
        http.verboseLogging = false
        var certPem: String? = http.quickGetStr(url: certUrl.getAsString())
        if (http.lastMethodSuccess != true) || (http.lastStatus.intValue != 200) {
            print("Could not retrieve the certificate securely from the pinned SNS endpoint.")
            return
        }

        let signingCert = CkoCert()!
        success = signingCert.loadPem(strPem: certPem)
        if success != true {
            print("Invalid signing certificate.")
            return
        }

        let chain = CkoCertChain()!
        success = signingCert.buildChain(certChain: chain)
        if success != true {
            print("Could not build signing-certificate chain.")
            return
        }

        if chain.reachesRoot != true {
            print("Incomplete signing-certificate chain; provision trusted intermediates.")
            return
        }

        let roots = CkoTrustedRoots()!
        roots.trustSystemCaRoots = true
        if chain.isRootTrusted(trustedRoots: roots) != true {
            print("Untrusted signing-certificate root.")
            return
        }

        success = chain.verifyCertSignatures()
        if success != true {
            print("Invalid certificate-chain signatures.")
            return
        }

        var certIndex: Int = 0
        let chainCert = CkoCert()!
        while (certIndex < chain.numCerts.intValue) {
            success = chain.cert(at: certIndex, cert: chainCert)
            if success != true {
                print("Could not read chain certificate.")
                return
            }

            let validFrom = CkoDateTime()!
            let validTo = CkoDateTime()!
            success = validFrom.set(fromRfc822: chainCert.validFromStr)
            if success != true {
                print("Invalid certificate validity start.")
                return
            }

            success = validTo.set(fromRfc822: chainCert.validToStr)
            if success != true {
                print("Invalid certificate validity end.")
                return
            }

            if (now.diffSeconds(dateTimeArg: validFrom).intValue < 0) || (now.diffSeconds(dateTimeArg: validTo).intValue > 0) {
                print("Certificate outside its validity period.")
                return
            }

            certIndex = certIndex + 1
        }

        let canonical = CkoStringBuilder()!
        canonical.appendLine(str: "Message", crlf: false)
        canonical.appendLine(str: envelope.string(of: "Message"), crlf: false)
        canonical.appendLine(str: "MessageId", crlf: false)
        canonical.appendLine(str: envelope.string(of: "MessageId"), crlf: false)
        stringCompare.setString(value: messageType)
        var stringMatch19: Bool = stringCompare.contentsEqual(str: "Notification", caseSensitive: true)
        if stringMatch19 == true {
            if envelope.hasMember(jsonPath: "Subject") == true {
                canonical.appendLine(str: "Subject", crlf: false)
                canonical.appendLine(str: envelope.string(of: "Subject"), crlf: false)
            }

        }
        else {
            canonical.appendLine(str: "SubscribeURL", crlf: false)
            canonical.appendLine(str: envelope.string(of: "SubscribeURL"), crlf: false)
        }

        canonical.appendLine(str: "Timestamp", crlf: false)
        canonical.appendLine(str: envelope.string(of: "Timestamp"), crlf: false)
        stringCompare.setString(value: messageType)
        var stringMatch20: Bool = stringCompare.contentsEqual(str: "Notification", caseSensitive: true)
        if stringMatch20 != true {
            canonical.appendLine(str: "Token", crlf: false)
            canonical.appendLine(str: envelope.string(of: "Token"), crlf: false)
        }

        canonical.appendLine(str: "TopicArn", crlf: false)
        canonical.appendLine(str: envelope.string(of: "TopicArn"), crlf: false)
        canonical.appendLine(str: "Type", crlf: false)
        canonical.appendLine(str: envelope.string(of: "Type"), crlf: false)
        let publicKey = CkoPublicKey()!
        success = signingCert.getPublicKey(pubKey: publicKey)
        if success != true {
            print("Could not extract signing public key.")
            return
        }

        let rsa = CkoRsa()!
        rsa.charset = "utf-8"
        rsa.encodingMode = "base64"
        rsa.littleEndian = false
        success = rsa.usePublicKey(pubKey: publicKey)
        if success != true {
            print("Could not configure verification key.")
            return
        }

        success = rsa.verifyStringENC(str: canonical.getAsString(), hashAlg: hashAlgorithm, sig: envelope.string(of: "Signature"))
        if success != true {
            print("SNS delivery signature is invalid.")
            return
        }

        //  Use a JSON-encoded composite key to avoid ambiguous concatenation.
        let identity = CkoJsonObject()!
        success = identity.updateString(jsonPath: "topic", value: allowedTopic)
        if success != true {
            print("Could not form duplicate key.")
            return
        }

        success = identity.updateString(jsonPath: "id", value: envelope.string(of: "MessageId"))
        if success != true {
            print("Could not form duplicate key.")
            return
        }

        var duplicateKey: String? = identity.emit()
        if seenMessages.contains(key: duplicateKey) == true {
            print("Verified duplicate skipped: \(envelope.string(of: "MessageId")!)")
        }
        else {
            success = seenMessages.addStr(key: duplicateKey, value: "verified")
            if success != true {
                print("Could not track duplicate key.")
                return
            }

            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.
        }

        envelopeIndex = envelopeIndex + 1
    }

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

}