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

Java
import com.chilkatsoft.chilkat2.Cert;
import com.chilkatsoft.chilkat2.CertChain;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.DateTime;
import com.chilkatsoft.chilkat2.Hashtable;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.PublicKey;
import com.chilkatsoft.chilkat2.Rsa;
import com.chilkatsoft.chilkat2.StringBuilder;
import com.chilkatsoft.chilkat2.TrustedRoots;

public class ChilkatExample {

    public static void main(String[] args) {
        boolean success = false;

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

        JsonObject batch = new JsonObject();
        batch.setStrict(true);
        try {
            batch.loadFile("qa_data/aws/sns_notifications.json");
        } catch (ChilkatException e) {
            System.out.println("Could not parse notification envelopes.");
            return;
        }

        if (batch.jsonTypeOf("messages") != 4) {
            System.out.println("Expected a messages array.");
            return;
        }

        int count = batch.sizeOfArray("messages");
        if ((count < 1) || (count > 100)) {
            System.out.println("Use 1 to 100 envelopes per verification batch.");
            return;
        }

        String allowedTopic = "arn:aws:sns:us-west-2:123456789012:chilkat-standard-example";
        String certPrefix = "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-";
        // Pin the expected topic and matching regional SNS host in application configuration.
        Hashtable seenMessages = new Hashtable();
        JsonObject envelope = new JsonObject();
        DateTime now = new DateTime();
        try {
            now.setFromCurrentSystemTime();
        } catch (ChilkatException e) {
            System.out.println("Could not read current time.");
            return;
        }

        int envelopeIndex = 0;
        while (envelopeIndex < count) {
            batch.setI(envelopeIndex);
            try {
                batch.objectOf2("messages[i]", envelope);
            } catch (ChilkatException e) {
                System.out.println("Expected a JSON object envelope.");
                return;
            }

            Hashtable fieldNames = new Hashtable();
            int fieldIndex = 0;
            while (fieldIndex < envelope.getSize()) {
                String fieldName = envelope.nameAt(fieldIndex);
                if (fieldNames.contains(fieldName)) {
                    System.out.println("Duplicate envelope field.");
                    return;
                }

                try {
                    fieldNames.addStr(fieldName, "seen");
                } catch (ChilkatException e) {
                    System.out.println("Could not track envelope fields.");
                    return;
                }

                fieldIndex = fieldIndex + 1;
            }

            stringCompare.setString(envelope.stringOf("Type"));
            boolean stringMatch1 = stringCompare.contentsEqual("", true);
            if ((envelope.jsonTypeOf("Type") != 1) || (stringMatch1)) {
                System.out.println("Missing or invalid Type.");
                return;
            }

            stringCompare.setString(envelope.stringOf("MessageId"));
            boolean stringMatch2 = stringCompare.contentsEqual("", true);
            if ((envelope.jsonTypeOf("MessageId") != 1) || (stringMatch2)) {
                System.out.println("Missing or invalid MessageId.");
                return;
            }

            stringCompare.setString(envelope.stringOf("Message"));
            boolean stringMatch3 = stringCompare.contentsEqual("", true);
            if ((envelope.jsonTypeOf("Message") != 1) || (stringMatch3)) {
                System.out.println("Missing or invalid Message.");
                return;
            }

            stringCompare.setString(envelope.stringOf("Timestamp"));
            boolean stringMatch4 = stringCompare.contentsEqual("", true);
            if ((envelope.jsonTypeOf("Timestamp") != 1) || (stringMatch4)) {
                System.out.println("Missing or invalid Timestamp.");
                return;
            }

            stringCompare.setString(envelope.stringOf("TopicArn"));
            boolean stringMatch5 = stringCompare.contentsEqual("", true);
            if ((envelope.jsonTypeOf("TopicArn") != 1) || (stringMatch5)) {
                System.out.println("Missing or invalid TopicArn.");
                return;
            }

            stringCompare.setString(envelope.stringOf("SignatureVersion"));
            boolean stringMatch6 = stringCompare.contentsEqual("", true);
            if ((envelope.jsonTypeOf("SignatureVersion") != 1) || (stringMatch6)) {
                System.out.println("Missing or invalid SignatureVersion.");
                return;
            }

            stringCompare.setString(envelope.stringOf("Signature"));
            boolean stringMatch7 = stringCompare.contentsEqual("", true);
            if ((envelope.jsonTypeOf("Signature") != 1) || (stringMatch7)) {
                System.out.println("Missing or invalid Signature.");
                return;
            }

            stringCompare.setString(envelope.stringOf("SigningCertURL"));
            boolean stringMatch8 = stringCompare.contentsEqual("", true);
            if ((envelope.jsonTypeOf("SigningCertURL") != 1) || (stringMatch8)) {
                System.out.println("Missing or invalid SigningCertURL.");
                return;
            }

            String messageType = envelope.stringOf("Type");
            stringCompare.setString(messageType);
            boolean stringMatch9 = stringCompare.contentsEqual("Notification", true);
            stringCompare.setString(messageType);
            boolean stringMatch10 = stringCompare.contentsEqual("SubscriptionConfirmation", true);
            stringCompare.setString(messageType);
            boolean stringMatch11 = stringCompare.contentsEqual("UnsubscribeConfirmation", true);
            if ((!stringMatch9) && ((!stringMatch10) && (!stringMatch11))) {
                System.out.println("Unsupported SNS message type.");
                return;
            }

            stringCompare.setString(envelope.stringOf("TopicArn"));
            boolean stringMatch12 = stringCompare.contentsEqual(allowedTopic, true);
            if (!stringMatch12) {
                System.out.println("Unexpected SNS topic.");
                return;
            }

            String signatureVersion = envelope.stringOf("SignatureVersion");
            stringCompare.setString(signatureVersion);
            boolean stringMatch13 = stringCompare.contentsEqual("1", true);
            stringCompare.setString(signatureVersion);
            boolean stringMatch14 = stringCompare.contentsEqual("2", true);
            if ((!stringMatch13) && (!stringMatch14)) {
                System.out.println("Unsupported delivery signature version.");
                return;
            }

            String hashAlgorithm = "sha256";
            stringCompare.setString(signatureVersion);
            boolean stringMatch15 = stringCompare.contentsEqual("1", true);
            if (stringMatch15) {
                hashAlgorithm = "sha1";
            }

            stringCompare.setString(messageType);
            boolean stringMatch16 = stringCompare.contentsEqual("Notification", true);
            if (!stringMatch16) {
                stringCompare.setString(envelope.stringOf("SubscribeURL"));
                boolean stringMatch17 = stringCompare.contentsEqual("", true);
                stringCompare.setString(envelope.stringOf("Token"));
                boolean stringMatch18 = stringCompare.contentsEqual("", true);
                if ((envelope.jsonTypeOf("SubscribeURL") != 1) || ((stringMatch17) || ((envelope.jsonTypeOf("Token") != 1) || (stringMatch18)))) {
                    System.out.println("Confirmation envelope is missing fields.");
                    return;
                }
            }

            if (envelope.hasMember("Subject")) {
                if (envelope.jsonTypeOf("Subject") != 1) {
                    System.out.println("Subject must be a string when present.");
                    return;
                }
            }

            DateTime timestamp = new DateTime();
            try {
                timestamp.setFromTimestamp(envelope.stringOf("Timestamp"));
            } catch (ChilkatException e) {
                System.out.println("Invalid notification timestamp.");
                return;
            }

            int ageSeconds = now.diffSeconds(timestamp);
            if ((ageSeconds < -300) || (ageSeconds > 86400)) {
                System.out.println("Notification outside the configured 24-hour age / 5-minute clock-skew window.");
                return;
            }

            StringBuilder certUrl = new StringBuilder();
            certUrl.append(envelope.stringOf("SigningCertURL"));
            StringBuilder prefix = new StringBuilder();
            prefix.append(certPrefix);
            if ((!certUrl.startsWith(certPrefix, true)) || ((!certUrl.endsWith(".pem", true)) || (certUrl.getLength() <= prefix.getLength() + 4))) {
                System.out.println("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.
            StringBuilder filenameChars = new StringBuilder();
            filenameChars.append("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_");
            int charIndex = prefix.getLength();
            while (charIndex < certUrl.getLength() - 4) {
                if (!filenameChars.contains(certUrl.getRange(charIndex, 1, false), true)) {
                    System.out.println("Invalid signing-certificate filename.");
                    return;
                }

                charIndex = charIndex + 1;
            }

            Http http = new Http();
            http.setRequireSslCertVerify(true);
            http.setFollowRedirects(false);
            http.setConnectTimeout(20);
            http.setReadTimeout(30);
            long maxCertBytes = 65536;
            http.setMaxResponseSize(maxCertBytes);
            http.setVerboseLogging(false);
            String certPem = http.quickGetStr(certUrl.getAsString());
            if ((!http.getLastMethodSuccess()) || (http.getLastStatus() != 200)) {
                System.out.println("Could not retrieve the certificate securely from the pinned SNS endpoint.");
                return;
            }

            Cert signingCert = new Cert();
            try {
                signingCert.loadPem(certPem);
            } catch (ChilkatException e) {
                System.out.println("Invalid signing certificate.");
                return;
            }

            CertChain chain = new CertChain();
            try {
                signingCert.buildCertChain(chain);
            } catch (ChilkatException e) {
                System.out.println("Could not build signing-certificate chain.");
                return;
            }

            if (!chain.getReachesRoot()) {
                System.out.println("Incomplete signing-certificate chain; provision trusted intermediates.");
                return;
            }

            TrustedRoots roots = new TrustedRoots();
            roots.setTrustSystemCaRoots(true);
            if (!chain.isRootTrusted(roots)) {
                System.out.println("Untrusted signing-certificate root.");
                return;
            }

            success = chain.verifyCertSignatures();
            if (!success) {
                System.out.println("Invalid certificate-chain signatures.");
                return;
            }

            int certIndex = 0;
            Cert chainCert = new Cert();
            while (certIndex < chain.getNumCerts()) {
                try {
                    chain.certAt(certIndex, chainCert);
                } catch (ChilkatException e) {
                    System.out.println("Could not read chain certificate.");
                    return;
                }

                DateTime validFrom = new DateTime();
                DateTime validTo = new DateTime();
                try {
                    validFrom.setFromRfc822(chainCert.getValidFromStr());
                } catch (ChilkatException e) {
                    System.out.println("Invalid certificate validity start.");
                    return;
                }

                try {
                    validTo.setFromRfc822(chainCert.getValidToStr());
                } catch (ChilkatException e) {
                    System.out.println("Invalid certificate validity end.");
                    return;
                }

                if ((now.diffSeconds(validFrom) < 0) || (now.diffSeconds(validTo) > 0)) {
                    System.out.println("Certificate outside its validity period.");
                    return;
                }

                certIndex = certIndex + 1;
            }

            StringBuilder canonical = new StringBuilder();
            canonical.appendLine("Message", false);
            canonical.appendLine(envelope.stringOf("Message"), false);
            canonical.appendLine("MessageId", false);
            canonical.appendLine(envelope.stringOf("MessageId"), false);
            stringCompare.setString(messageType);
            boolean stringMatch19 = stringCompare.contentsEqual("Notification", true);
            if (stringMatch19) {
                if (envelope.hasMember("Subject")) {
                    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);
            boolean stringMatch20 = stringCompare.contentsEqual("Notification", true);
            if (!stringMatch20) {
                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 publicKey = new PublicKey();
            try {
                signingCert.getPublicKey(publicKey);
            } catch (ChilkatException e) {
                System.out.println("Could not extract signing public key.");
                return;
            }

            Rsa rsa = new Rsa();
            rsa.setCharset("utf-8");
            rsa.setEncodingMode("base64");
            rsa.setLittleEndian(false);
            try {
                rsa.usePublicKey(publicKey);
            } catch (ChilkatException e) {
                System.out.println("Could not configure verification key.");
                return;
            }

            try {
                rsa.verifyStringENC(canonical.getAsString(), hashAlgorithm, envelope.stringOf("Signature"));
            } catch (ChilkatException e) {
                System.out.println("SNS delivery signature is invalid.");
                return;
            }

            // Use a JSON-encoded composite key to avoid ambiguous concatenation.
            JsonObject identity = new JsonObject();
            try {
                identity.updateString("topic", allowedTopic);

                identity.updateString("id", envelope.stringOf("MessageId"));
            } catch (ChilkatException e) {
                System.out.println("Could not form duplicate key.");
                return;
            }

            String duplicateKey = identity.emit();
            if (seenMessages.contains(duplicateKey)) {
                System.out.println("Verified duplicate skipped: " + envelope.stringOf("MessageId"));
            } else {
                try {
                    seenMessages.addStr(duplicateKey, "verified");
                } catch (ChilkatException e) {
                    System.out.println("Could not track duplicate key.");
                    return;
                }

                System.out.println("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;
        }

        System.out.println("All envelopes verified; duplicate detection was limited to this batch.");
    }
}