feat(sns): sign deliveries with a served RSA certificate like AWS (#5189)

* feat(sns): sign deliveries with a served RSA certificate like AWS

Replace the EXAMPLE Signature and SigningCertURL placeholders with real
signatures over the documented canonical string. Notifications and
subscription confirmations delivered to HTTP/HTTPS endpoints, Lambda
records and non-raw SQS envelopes are signed with SHA1withRSA, or
SHA256withRSA when the topic sets SignatureVersion to 2.

The RSA 2048 key and its self-signed certificate are kept in SNS storage
and the certificate is served at
/_aws/sns/SimpleNotificationService-<fingerprint>.pem, so a new key always
gets a new URL. The SQS envelope now carries UnsubscribeURL and the Lambda
record a real UnsubscribeUrl, as on AWS.

* fix(sns): drop a delivery when signing fails and regenerate the key on reset

A signing failure in the Lambda, SQS and HTTP builders was caught with the JSON
fallback and delivered an empty placeholder as if it had succeeded. Only a JSON
serialization error falls back now; a signing failure fails that delivery.

SnsMessageSigner is now Resettable: a reset drops the cached key instead of
writing it back to the cleared store, so the next delivery generates a new one.

* style(sns): sort SnsService imports

* refactor(sns): build the SQS envelope with the builder Firehose uses

buildSnsSqsEnvelope duplicated buildSnsEnvelope apart from the signature and UnsubscribeURL. buildSnsEnvelope now takes the subscription ARN and signature version and adds both only when a subscription is given, so SQS and Firehose share one builder again.
This commit is contained in:
Salil Chincholikar authored and GitHub committed 2026-10-06 22:50:56 -04:00
1 parent 1b61945f28
commit c0b2b299b0
8 files changed
+840 -35

No files matched your search

+24
View File
@@ -125,6 +125,30 @@ address is not screened at delivery: Floci's HTTP client resolves the name itsel
and cannot be given the result of an earlier check, so a lookup there could not decide where the
request goes. Treat the `Subscribe` check as the boundary, not the delivery one.
## Message signatures
Floci signs deliveries the way AWS does, so a consumer can keep its standard SNS signature check
switched on locally. Signed messages are HTTP/HTTPS notifications and `SubscriptionConfirmation`
messages, Lambda records, and the JSON envelope SQS subscriptions receive without
`RawMessageDelivery`.
- `Signature` is the base64 RSA signature of the canonical string AWS documents: `Name\nValue\n`
for `Message`, `MessageId`, `Subject` (only when present), `Timestamp`, `TopicArn` and `Type` on a
notification, and `Message`, `MessageId`, `SubscribeURL`, `Timestamp`, `Token`, `TopicArn` and
`Type` on a confirmation.
- `SignatureVersion` follows the topic attribute of the same name: `1` (default) is SHA1withRSA,
`2` is SHA256withRSA.
- `SigningCertURL` (`SigningCertUrl` in Lambda records) points at a self-signed RSA 2048
certificate Floci serves itself:
`{base-url}/_aws/sns/SimpleNotificationService-<fingerprint>.pem`.
The key is kept in SNS storage, so persistent storage keeps the same certificate across restarts
and memory storage generates a new one per process. A state reset discards the key and the next
delivery generates a new one. The fingerprint in the file name changes with
the key, so a consumer that caches certificates by URL never verifies against a stale one. A
consumer that also requires the certificate host to be an AWS SNS domain must relax that check
locally.
## Message size
`MaximumMessageSize` is the per-topic limit, in bytes, on a published payload. It accepts `1024`
@@ -8,6 +8,7 @@ import jakarta.inject.Inject;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
@@ -24,18 +25,34 @@ import java.util.List;
* <p>GET /_aws/sns?phone=X — filter by phone number (URL-encoded)
* <p>GET /_aws/sns?id=X — filter by message ID
* <p>DELETE /_aws/sns — clear all stored SMS
* <p>GET /_aws/sns/SimpleNotificationService-&lt;fingerprint&gt;.pem: the certificate deliveries
* are signed with, the {@code SigningCertURL} of every signed message
*/
@Path("/_aws/sns")
@Produces(MediaType.APPLICATION_JSON)
public class SnsInspectionController {
private static final String PEM_MEDIA_TYPE = "application/x-pem-file";
private final SnsService snsService;
private final ObjectMapper objectMapper;
private final SnsMessageSigner messageSigner;
@Inject
public SnsInspectionController(SnsService snsService, ObjectMapper objectMapper) {
public SnsInspectionController(SnsService snsService, ObjectMapper objectMapper,
SnsMessageSigner messageSigner) {
this.snsService = snsService;
this.objectMapper = objectMapper;
this.messageSigner = messageSigner;
}
@GET
@Path("{certificate: SimpleNotificationService-[0-9a-f]+\\.pem}")
@Produces(PEM_MEDIA_TYPE)
public Response getSigningCertificate(@PathParam("certificate") String certificate) {
return messageSigner.certificatePem(certificate)
.map(pem -> Response.ok(pem, PEM_MEDIA_TYPE).build())
.orElseGet(() -> Response.status(Response.Status.NOT_FOUND).build());
}
@GET
@@ -0,0 +1,219 @@
package io.github.hectorvent.floci.services.sns;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.Pem;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.sns.model.SnsSigningKey;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.bouncycastle.asn1.x500.X500Name;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Signs SNS deliveries the way AWS does, so a consumer can verify them with the standard SNS
* signature check instead of switching verification off locally.
*
* <p>The canonical string is the documented {@code Name\nValue\n} sequence over the fields of the
* message type, signed with SHA1withRSA ({@code SignatureVersion} 1) or SHA256withRSA (2). The
* certificate is a self-signed RSA 2048 certificate served at
* {@code {base-url}/_aws/sns/SimpleNotificationService-<fingerprint>.pem}. The file name carries
* the certificate's fingerprint, as AWS's does, so a new key always gets a new URL and a consumer
* that caches certificates by URL can never verify against a stale one.
*/
@ApplicationScoped
public class SnsMessageSigner implements Resettable {
private static final Logger LOG = Logger.getLogger(SnsMessageSigner.class);
static final String CERTIFICATE_PATH = "/_aws/sns/";
static final String CERTIFICATE_PREFIX = "SimpleNotificationService-";
static final String CERTIFICATE_SUFFIX = ".pem";
static final String SIGNATURE_VERSION_1 = "1";
static final String SIGNATURE_VERSION_2 = "2";
private static final String STORE_KEY = "signing-key";
private static final String COMMON_NAME = "CN=Floci SNS Signing";
private static final int VALIDITY_DAYS = 3650;
private static final List<String> NOTIFICATION_FIELDS =
List.of("Message", "MessageId", "Subject", "Timestamp", "TopicArn", "Type");
private static final List<String> CONFIRMATION_FIELDS =
List.of("Message", "MessageId", "SubscribeURL", "Timestamp", "Token", "TopicArn", "Type");
private final AccountAwareStorageBackend<SnsSigningKey> keyStore;
private final String storeAccountId;
private final CertificateGenerator certificateGenerator;
private final String baseUrl;
private volatile Material material;
private record Material(SnsSigningKey stored, PrivateKey privateKey, String fileName) {}
@Inject
public SnsMessageSigner(StorageFactory storageFactory, EmulatorConfig config,
CertificateGenerator certificateGenerator) {
this(storageFactory.create("sns", "sns-signing-keys.json",
new TypeReference<Map<String, SnsSigningKey>>() {
}),
config.defaultAccountId(), certificateGenerator, config.effectiveBaseUrl());
}
SnsMessageSigner(AccountAwareStorageBackend<SnsSigningKey> keyStore, String storeAccountId,
CertificateGenerator certificateGenerator, String baseUrl) {
this.keyStore = keyStore;
this.storeAccountId = storeAccountId;
this.certificateGenerator = certificateGenerator;
this.baseUrl = baseUrl;
}
/** A signer with its own in-memory key, for services built outside CDI. */
static SnsMessageSigner inMemory(String baseUrl) {
String accountId = "000000000000";
return new SnsMessageSigner(AccountAwareStorageBackend.inMemory(accountId), accountId,
new CertificateGenerator(), baseUrl);
}
/** {@code 2} when the topic asks for SHA256withRSA, otherwise AWS's default {@code 1}. */
static String normalizeSignatureVersion(String topicSignatureVersion) {
return SIGNATURE_VERSION_2.equals(topicSignatureVersion) ? SIGNATURE_VERSION_2 : SIGNATURE_VERSION_1;
}
/**
* Appends {@code SignatureVersion}, {@code Signature} and the certificate URL field to a
* message whose canonical fields are already set. {@code certUrlField} is
* {@code SigningCertURL} for HTTP and SQS envelopes, {@code SigningCertUrl} in Lambda records.
*/
public void sign(ObjectNode node, String signatureVersion, String certUrlField) {
String version = normalizeSignatureVersion(signatureVersion);
Material current = material();
node.put("SignatureVersion", version);
node.put("Signature", signature(canonicalString(node), version, current.privateKey()));
node.put(certUrlField, baseUrl + CERTIFICATE_PATH + current.fileName());
}
/** The absolute URL of the certificate deliveries are currently signed with. */
public String certificateUrl() {
return baseUrl + CERTIFICATE_PATH + material().fileName();
}
/** The PEM certificate when {@code fileName} names the current one, otherwise empty. */
public Optional<String> certificatePem(String fileName) {
Material current = material();
if (current.fileName().equals(fileName)) {
return Optional.of(current.stored().getCertificatePem());
}
return Optional.empty();
}
/** Drops the cached key, so the next delivery after a reset generates and stores a new one. */
@Override
public synchronized void clear() {
material = null;
}
static String canonicalString(JsonNode node) {
String type = node.path("Type").asText("");
List<String> fields = "Notification".equals(type) ? NOTIFICATION_FIELDS : CONFIRMATION_FIELDS;
StringBuilder canonical = new StringBuilder();
for (String field : fields) {
JsonNode value = node.get(field);
if (value == null || value.isNull()) {
continue;
}
canonical.append(field).append('\n').append(value.asText()).append('\n');
}
return canonical.toString();
}
static String signatureAlgorithm(String signatureVersion) {
return SIGNATURE_VERSION_2.equals(signatureVersion) ? "SHA256withRSA" : "SHA1withRSA";
}
private static String signature(String canonical, String version, PrivateKey privateKey) {
try {
Signature signer = Signature.getInstance(signatureAlgorithm(version));
signer.initSign(privateKey);
signer.update(canonical.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(signer.sign());
} catch (GeneralSecurityException e) {
throw new IllegalStateException("Failed to sign SNS message", e);
}
}
private Material material() {
Material current = material;
if (current != null) {
return current;
}
synchronized (this) {
if (material == null) {
material = loadOrCreate();
}
return material;
}
}
private Material loadOrCreate() {
Optional<SnsSigningKey> stored = keyStore.getForAccount(storeAccountId, STORE_KEY);
if (stored.isPresent()) {
try {
Material loaded = toMaterial(stored.get());
LOG.debugv("Using stored SNS signing certificate {0}", loaded.fileName());
return loaded;
} catch (Exception e) {
LOG.warnv("Stored SNS signing key is unusable ({0}); generating a new one", e.getMessage());
}
}
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
KeyPair keyPair = generator.generateKeyPair();
X500Name name = new X500Name(COMMON_NAME);
X509Certificate certificate = certificateGenerator.signCertificate(name, keyPair.getPublic(), name,
keyPair.getPrivate(), List.of(), false, null, VALIDITY_DAYS);
SnsSigningKey key = new SnsSigningKey(certificateGenerator.toPem(certificate),
certificateGenerator.toPem(keyPair.getPrivate()));
Material created = toMaterial(key);
keyStore.putForAccount(storeAccountId, STORE_KEY, key);
LOG.infov("Generated SNS signing certificate {0}", created.fileName());
return created;
} catch (Exception e) {
throw new IllegalStateException("Failed to generate the SNS signing key", e);
}
}
private static Material toMaterial(SnsSigningKey key) throws Exception {
X509Certificate certificate = Pem.parseCertificate(key.getCertificatePem());
PrivateKey privateKey = Pem.parsePrivateKey(key.getPrivateKeyPem());
if (!Pem.isPair(privateKey, certificate.getPublicKey())) {
throw new IllegalStateException("private key does not match the certificate");
}
return new Material(key, privateKey, CERTIFICATE_PREFIX + fingerprint(certificate) + CERTIFICATE_SUFFIX);
}
private static String fingerprint(X509Certificate certificate) {
try {
byte[] digest = MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded());
return HexFormat.of().formatHex(digest, 0, 16);
} catch (GeneralSecurityException e) {
throw new IllegalStateException("Cannot fingerprint the SNS signing certificate", e);
}
}
}
@@ -1,5 +1,11 @@
package io.github.hectorvent.floci.services.sns;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
@@ -11,13 +17,13 @@ import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
import io.github.hectorvent.floci.services.firehose.model.Record;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.sns.model.PlatformApplication;
import io.github.hectorvent.floci.services.sns.model.PlatformEndpoint;
import io.github.hectorvent.floci.services.sns.model.PushNotification;
@@ -26,11 +32,6 @@ import io.github.hectorvent.floci.services.sns.model.Subscription;
import io.github.hectorvent.floci.services.sns.model.Topic;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -126,6 +127,7 @@ public class SnsService implements Resettable, ResourceProvider {
private final String baseUrl;
private final ObjectMapper objectMapper;
private final HttpClient httpClient;
private final SnsMessageSigner messageSigner;
private final Map<String, Instant> fifoDeduplicationCache = new ConcurrentHashMap<>();
private static final HexFormat HEX = HexFormat.of();
@@ -133,7 +135,7 @@ public class SnsService implements Resettable, ResourceProvider {
public SnsService(StorageFactory storageFactory, EmulatorConfig config,
RegionResolver regionResolver, SqsService sqsService,
LambdaService lambdaService, FirehoseService firehoseService,
ObjectMapper objectMapper) {
ObjectMapper objectMapper, SnsMessageSigner messageSigner) {
this(
storageFactory.create("sns", "sns-topics.json",
new TypeReference<Map<String, Topic>>() {
@@ -158,7 +160,8 @@ public class SnsService implements Resettable, ResourceProvider {
lambdaService,
firehoseService,
config.effectiveBaseUrl(),
objectMapper
objectMapper,
messageSigner
);
}
@@ -213,6 +216,7 @@ public class SnsService implements Resettable, ResourceProvider {
this.baseUrl = "http://localhost:4566";
this.objectMapper = new ObjectMapper();
this.httpClient = null;
this.messageSigner = SnsMessageSigner.inMemory(baseUrl);
}
SnsService(StorageBackend<String, Topic> topicStore,
@@ -248,6 +252,20 @@ public class SnsService implements Resettable, ResourceProvider {
RegionResolver regionResolver, SqsService sqsService,
LambdaService lambdaService, FirehoseService firehoseService,
String baseUrl, ObjectMapper objectMapper) {
this(topicStore, subscriptionStore, platformAppStore, platformEndpointStore, smsStore,
smsAttributesStore, regionResolver, sqsService, lambdaService, firehoseService,
baseUrl, objectMapper, SnsMessageSigner.inMemory(baseUrl));
}
SnsService(StorageBackend<String, Topic> topicStore,
StorageBackend<String, Subscription> subscriptionStore,
StorageBackend<String, PlatformApplication> platformAppStore,
StorageBackend<String, PlatformEndpoint> platformEndpointStore,
StorageBackend<String, SentSms> smsStore,
StorageBackend<String, Map<String, String>> smsAttributesStore,
RegionResolver regionResolver, SqsService sqsService,
LambdaService lambdaService, FirehoseService firehoseService,
String baseUrl, ObjectMapper objectMapper, SnsMessageSigner messageSigner) {
this.topicStore = topicStore;
this.subscriptionStore = subscriptionStore;
this.platformAppStore = platformAppStore;
@@ -261,6 +279,7 @@ public class SnsService implements Resettable, ResourceProvider {
this.baseUrl = baseUrl;
this.objectMapper = objectMapper;
this.httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
this.messageSigner = messageSigner;
}
public void clear() {
@@ -734,7 +753,8 @@ public class SnsService implements Resettable, ResourceProvider {
if (!matchesFilterPolicy(sub, parsedBody, messageAttributes)) {
continue;
}
deliverMessage(sub, message, subject, messageAttributes, messageId, effectiveArn, messageGroupId, dedupId, messageStructure);
deliverMessage(sub, message, subject, messageAttributes, messageId, effectiveArn, messageGroupId, dedupId, messageStructure,
signatureVersion(topic));
}
LOG.infov("Published message {0} to topic {1}", messageId, effectiveArn);
return messageId;
@@ -1196,7 +1216,8 @@ public class SnsService implements Resettable, ResourceProvider {
bodyParseAttempted = true;
}
if (!matchesFilterPolicy(sub, parsedBody, attrs)) continue;
deliverMessage(sub, message, subject, attrs, messageId, topicArn, messageGroupId, messageDeduplicationId, messageStructure);
deliverMessage(sub, message, subject, attrs, messageId, topicArn, messageGroupId, messageDeduplicationId, messageStructure,
signatureVersion(topic));
}
LOG.debugv("Batch published message {0} (id={1}) to {2}", messageId, id, topicArn);
successful.add(new String[]{id, messageId});
@@ -1803,7 +1824,7 @@ public class SnsService implements Resettable, ResourceProvider {
private void deliverMessage(Subscription sub, String message, String subject,
Map<String, MessageAttributeValue> messageAttributes, String messageId,
String topicArn, String messageGroupId, String messageDeduplicationId,
String messageStructure) {
String messageStructure, String signatureVersion) {
try {
// Under MessageStructure="json" every subscriber gets the value under its own
// protocol key, falling back to "default". The application case resolves against
@@ -1821,7 +1842,8 @@ public class SnsService implements Resettable, ResourceProvider {
boolean rawDelivery = "true".equalsIgnoreCase(sub.getAttributes().get("RawMessageDelivery"));
String body = rawDelivery
? protocolMessage
: buildSnsEnvelope(protocolMessage, subject, messageAttributes, topicArn, messageId);
: buildSnsEnvelope(protocolMessage, subject, messageAttributes, topicArn, messageId,
sub.getSubscriptionArn(), signatureVersion);
Map<String, MessageAttributeValue> sqsAttributes = rawDelivery
? toSqsMessageAttributes(messageAttributes)
: Collections.emptyMap();
@@ -1831,7 +1853,7 @@ public class SnsService implements Resettable, ResourceProvider {
case "lambda" -> {
String region = extractRegionFromArn(sub.getEndpoint());
String eventJson = buildSnsLambdaEvent(topicArn, messageId, protocolMessage,
subject, messageAttributes, sub.getSubscriptionArn());
subject, messageAttributes, sub.getSubscriptionArn(), signatureVersion);
lambdaService.invoke(region, sub.getEndpoint(), eventJson.getBytes(), InvocationType.Event);
LOG.debugv("Delivered SNS message to Lambda: {0}", sub.getEndpoint());
}
@@ -1842,7 +1864,8 @@ public class SnsService implements Resettable, ResourceProvider {
boolean rawDelivery = "true".equalsIgnoreCase(sub.getAttributes().get("RawMessageDelivery"));
String body = rawDelivery
? protocolMessage
: buildSnsHttpNotification(protocolMessage, subject, messageAttributes, topicArn, messageId, sub.getSubscriptionArn());
: buildSnsHttpNotification(protocolMessage, subject, messageAttributes, topicArn, messageId,
sub.getSubscriptionArn(), signatureVersion);
HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
.uri(URI.create(sub.getEndpoint()))
.timeout(Duration.ofSeconds(5))
@@ -1917,7 +1940,8 @@ public class SnsService implements Resettable, ResourceProvider {
&& "true".equalsIgnoreCase(sub.getAttributes().get("RawMessageDelivery"));
String body = rawDelivery
? protocolMessage
: buildSnsEnvelope(protocolMessage, subject, messageAttributes, topicArn, messageId);
: buildSnsEnvelope(protocolMessage, subject, messageAttributes, topicArn, messageId,
null, null);
byte[] data = body.getBytes(StandardCharsets.UTF_8);
firehoseService.putRecord(accountId, region, streamName, new Record(data));
LOG.debugv("Delivered SNS message to Firehose: {0} ({1}) raw={2}", sub.getEndpoint(), streamName, rawDelivery);
@@ -2011,7 +2035,7 @@ public class SnsService implements Resettable, ResourceProvider {
private String buildSnsLambdaEvent(String topicArn, String messageId, String message,
String subject, Map<String, MessageAttributeValue> messageAttributes,
String subscriptionArn) {
String subscriptionArn, String signatureVersion) {
try {
String timestamp = DateTimeFormatter.ISO_INSTANT.format(Instant.now());
ObjectNode snsNode = objectMapper.createObjectNode();
@@ -2025,10 +2049,8 @@ public class SnsService implements Resettable, ResourceProvider {
}
snsNode.put("Message", message);
snsNode.put("Timestamp", timestamp);
snsNode.put("SignatureVersion", "1");
snsNode.put("Signature", "EXAMPLE");
snsNode.put("SigningCertUrl", "EXAMPLE");
snsNode.put("UnsubscribeUrl", "EXAMPLE");
messageSigner.sign(snsNode, signatureVersion, "SigningCertUrl");
snsNode.put("UnsubscribeUrl", unsubscribeUrl(subscriptionArn));
ObjectNode attrs = snsNode.putObject("MessageAttributes");
if (messageAttributes != null) {
for (Map.Entry<String, MessageAttributeValue> entry : messageAttributes.entrySet()) {
@@ -2050,7 +2072,7 @@ public class SnsService implements Resettable, ResourceProvider {
ObjectNode root = objectMapper.createObjectNode();
root.putArray("Records").add(record);
return objectMapper.writeValueAsString(root);
} catch (Exception e) {
} catch (JsonProcessingException e) {
return "{\"Records\":[]}";
}
}
@@ -2070,9 +2092,15 @@ public class SnsService implements Resettable, ResourceProvider {
return new java.util.HashMap<>(snsAttributes);
}
/**
* The JSON notification envelope SQS and Firehose share. With a {@code subscriptionArn} it is
* signed and carries {@code UnsubscribeURL}, as a non-raw SQS delivery does; without one it is
* the unsigned form Firehose receives.
*/
private String buildSnsEnvelope(String message, String subject,
Map<String, MessageAttributeValue> messageAttributes,
String topicArn, String messageId) {
String topicArn, String messageId, String subscriptionArn,
String signatureVersion) {
try {
String timestamp = DateTimeFormatter.ISO_INSTANT.format(Instant.now());
ObjectNode node = objectMapper.createObjectNode();
@@ -2084,6 +2112,10 @@ public class SnsService implements Resettable, ResourceProvider {
node.put("Subject", subject);
}
node.put("Message", message);
if (subscriptionArn != null) {
messageSigner.sign(node, signatureVersion, "SigningCertURL");
node.put("UnsubscribeURL", unsubscribeUrl(subscriptionArn));
}
ObjectNode attrs = node.putObject("MessageAttributes");
if (messageAttributes != null) {
for (Map.Entry<String, MessageAttributeValue> entry : messageAttributes.entrySet()) {
@@ -2098,14 +2130,25 @@ public class SnsService implements Resettable, ResourceProvider {
}
}
return objectMapper.writeValueAsString(node);
} catch (Exception e) {
} catch (JsonProcessingException e) {
LOG.warnv("Failed to build SNS envelope for message {0}: {1}", messageId, e.getMessage());
return "{}";
}
}
private String unsubscribeUrl(String subscriptionArn) {
return baseUrl + "/?Action=Unsubscribe&SubscriptionArn=" + subscriptionArn;
}
private String signatureVersion(Topic topic) {
return SnsMessageSigner.normalizeSignatureVersion(
topic == null ? null : topic.getAttributes().get("SignatureVersion"));
}
private String buildSnsHttpNotification(String message, String subject,
Map<String, MessageAttributeValue> messageAttributes,
String topicArn, String messageId, String subscriptionArn) {
String topicArn, String messageId, String subscriptionArn,
String signatureVersion) {
try {
String timestamp = DateTimeFormatter.ISO_INSTANT.format(Instant.now());
ObjectNode node = objectMapper.createObjectNode();
@@ -2117,10 +2160,8 @@ public class SnsService implements Resettable, ResourceProvider {
node.put("Subject", subject);
}
node.put("Message", message);
node.put("SignatureVersion", "1");
node.put("Signature", "EXAMPLE");
node.put("SigningCertURL", "EXAMPLE");
node.put("UnsubscribeURL", baseUrl + "/?Action=Unsubscribe&SubscriptionArn=" + subscriptionArn);
messageSigner.sign(node, signatureVersion, "SigningCertURL");
node.put("UnsubscribeURL", unsubscribeUrl(subscriptionArn));
ObjectNode attrs = node.putObject("MessageAttributes");
if (messageAttributes != null) {
for (Map.Entry<String, MessageAttributeValue> entry : messageAttributes.entrySet()) {
@@ -2135,7 +2176,7 @@ public class SnsService implements Resettable, ResourceProvider {
}
}
return objectMapper.writeValueAsString(node);
} catch (Exception e) {
} catch (JsonProcessingException e) {
return "{}";
}
}
@@ -2162,9 +2203,8 @@ public class SnsService implements Resettable, ResourceProvider {
node.put("Message", "You have chosen to subscribe to the topic " + topicArn + ".\nTo confirm the subscription, visit the SubscribeURL included in this message.");
node.put("SubscribeURL", subscribeUrl);
node.put("Token", token);
node.put("SignatureVersion", "1");
node.put("Signature", "EXAMPLE");
node.put("SigningCertURL", "EXAMPLE");
messageSigner.sign(node, signatureVersion(topicStore.get(topicKey(region, topicArn)).orElse(null)),
"SigningCertURL");
String body = objectMapper.writeValueAsString(node);
HttpRequest request = HttpRequest.newBuilder()
@@ -0,0 +1,33 @@
package io.github.hectorvent.floci.services.sns.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* The RSA key pair and self-signed certificate SNS signs deliveries with, stored so a restart
* under persistent storage keeps signing with the certificate consumers have already fetched.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class SnsSigningKey {
@JsonProperty("CertificatePem")
private String certificatePem;
@JsonProperty("PrivateKeyPem")
private String privateKeyPem;
public SnsSigningKey() {}
public SnsSigningKey(String certificatePem, String privateKeyPem) {
this.certificatePem = certificatePem;
this.privateKeyPem = privateKeyPem;
}
public String getCertificatePem() { return certificatePem; }
public void setCertificatePem(String certificatePem) { this.certificatePem = certificatePem; }
public String getPrivateKeyPem() { return privateKeyPem; }
public void setPrivateKeyPem(String privateKeyPem) { this.privateKeyPem = privateKeyPem; }
}
@@ -198,8 +198,8 @@ class SnsHttpDeliveryIntegrationTest {
assertEquals("Hello HTTP endpoint!", envelope.get("Message").asText());
assertEquals("Test Subject", envelope.get("Subject").asText());
assertEquals("1", envelope.get("SignatureVersion").asText());
assertEquals("EXAMPLE", envelope.get("Signature").asText());
assertEquals("EXAMPLE", envelope.get("SigningCertURL").asText());
assertFalse(envelope.get("Signature").asText().isEmpty());
assertTrue(envelope.get("SigningCertURL").asText().endsWith(".pem"));
assertTrue(envelope.get("UnsubscribeURL").asText().contains("Action=Unsubscribe"));
assertNotNull(envelope.get("MessageId").asText());
assertNotNull(envelope.get("Timestamp").asText());
@@ -0,0 +1,267 @@
package io.github.hectorvent.floci.services.sns;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.net.httpserver.HttpServer;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ExtractableResponse;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.*;
/**
* Verifies SNS deliveries the way an AWS SDK message validator does: fetch the certificate from
* {@code SigningCertURL}, rebuild the canonical string for the message type, and check the
* base64 signature with SHA1withRSA ({@code SignatureVersion} 1) or SHA256withRSA (2).
*/
@QuarkusTest
class SnsMessageSignatureIntegrationTest {
private static final String BASE_URL = "http://localhost:4566";
private static final String CERT_PREFIX = BASE_URL + "/_aws/sns/SimpleNotificationService-";
private static final List<String> NOTIFICATION_FIELDS =
List.of("Message", "MessageId", "Subject", "Timestamp", "TopicArn", "Type");
private static final List<String> CONFIRMATION_FIELDS =
List.of("Message", "MessageId", "SubscribeURL", "Timestamp", "Token", "TopicArn", "Type");
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final List<String> received = new CopyOnWriteArrayList<>();
private static HttpServer httpServer;
private static int httpPort;
@BeforeAll
static void startHttpServer() throws IOException {
httpServer = HttpServer.create(new InetSocketAddress(0), 0);
httpPort = httpServer.getAddress().getPort();
httpServer.createContext("/signed", exchange -> {
received.add(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
exchange.sendResponseHeaders(200, 0);
exchange.close();
});
httpServer.start();
}
@AfterAll
static void stopHttpServer() {
if (httpServer != null) {
httpServer.stop(0);
}
}
@BeforeEach
void clearReceived() {
received.clear();
}
@Test
void httpConfirmationAndNotification_verifyAgainstServedCertificate() throws Exception {
String topicArn = createTopic("signed-http-topic");
subscribe(topicArn, "http", "http://localhost:" + httpPort + "/signed");
JsonNode confirmation = MAPPER.readTree(awaitMessage(0));
assertEquals("SubscriptionConfirmation", confirmation.get("Type").asText());
assertEquals("1", confirmation.get("SignatureVersion").asText());
assertTrue(verify(confirmation, "SigningCertURL"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ConfirmSubscription")
.formParam("TopicArn", topicArn)
.formParam("Token", confirmation.get("Token").asText())
.when()
.post("/")
.then()
.statusCode(200);
publish(topicArn, "Hello signed HTTP", "Signed subject");
JsonNode notification = MAPPER.readTree(awaitMessage(1));
assertEquals("Notification", notification.get("Type").asText());
assertEquals("Signed subject", notification.get("Subject").asText());
assertEquals("1", notification.get("SignatureVersion").asText());
assertTrue(verify(notification, "SigningCertURL"));
assertEquals(confirmation.get("SigningCertURL").asText(), notification.get("SigningCertURL").asText());
}
@Test
void sqsEnvelope_verifiesAndTamperedMessageFails() throws Exception {
String queueUrl = createQueue("signed-envelope-queue");
String topicArn = createTopic("signed-sqs-topic");
subscribe(topicArn, "sqs", queueUrl);
publish(topicArn, "Hello signed SQS", null);
JsonNode envelope = MAPPER.readTree(receiveBody(queueUrl));
assertEquals("Notification", envelope.get("Type").asText());
assertFalse(envelope.has("Subject"));
assertEquals("1", envelope.get("SignatureVersion").asText());
assertTrue(envelope.get("UnsubscribeURL").asText().contains("Action=Unsubscribe"));
assertTrue(verify(envelope, "SigningCertURL"));
ObjectNode tampered = envelope.deepCopy();
tampered.put("Message", "Hello forged SQS");
assertFalse(verify(tampered, "SigningCertURL"));
}
@Test
void signatureVersion2Topic_signsWithSha256() throws Exception {
String queueUrl = createQueue("signed-v2-queue");
String topicArn = createTopic("signed-v2-topic");
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SetTopicAttributes")
.formParam("TopicArn", topicArn)
.formParam("AttributeName", "SignatureVersion")
.formParam("AttributeValue", "2")
.when()
.post("/")
.then()
.statusCode(200);
subscribe(topicArn, "sqs", queueUrl);
publish(topicArn, "Hello SHA256", "v2");
JsonNode envelope = MAPPER.readTree(receiveBody(queueUrl));
assertEquals("2", envelope.get("SignatureVersion").asText());
assertTrue(verify(envelope, "SigningCertURL"));
assertFalse(verifyWith(envelope, "SigningCertURL", "SHA1withRSA"));
}
@Test
void unknownCertificateName_isNotFound() {
given()
.when()
.get("/_aws/sns/SimpleNotificationService-00000000000000000000000000000000.pem")
.then()
.statusCode(404);
}
private static boolean verify(JsonNode message, String certUrlField) throws Exception {
String algorithm = "2".equals(message.get("SignatureVersion").asText()) ? "SHA256withRSA" : "SHA1withRSA";
return verifyWith(message, certUrlField, algorithm);
}
private static boolean verifyWith(JsonNode message, String certUrlField, String algorithm) throws Exception {
String certUrl = message.get(certUrlField).asText();
assertTrue(certUrl.startsWith(CERT_PREFIX), certUrl);
assertTrue(certUrl.endsWith(".pem"), certUrl);
ExtractableResponse<Response> response = given()
.when()
.get(certUrl.substring(BASE_URL.length()))
.then()
.statusCode(200)
.extract();
assertTrue(response.contentType().startsWith("application/x-pem-file"), response.contentType());
X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509")
.generateCertificate(new ByteArrayInputStream(response.asByteArray()));
List<String> fields = "Notification".equals(message.get("Type").asText())
? NOTIFICATION_FIELDS
: CONFIRMATION_FIELDS;
StringBuilder canonical = new StringBuilder();
for (String field : fields) {
JsonNode value = message.get(field);
if (value != null && !value.isNull()) {
canonical.append(field).append('\n').append(value.asText()).append('\n');
}
}
Signature verifier = Signature.getInstance(algorithm);
verifier.initVerify(certificate.getPublicKey());
verifier.update(canonical.toString().getBytes(StandardCharsets.UTF_8));
return verifier.verify(Base64.getDecoder().decode(message.get("Signature").asText()));
}
private static String awaitMessage(int index) throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (received.size() <= index && System.nanoTime() < deadline) {
Thread.sleep(50);
}
assertTrue(received.size() > index, "no HTTP delivery #" + index);
return received.get(index);
}
private static String createTopic(String name) {
return given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateTopic")
.formParam("Name", name)
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");
}
private static String createQueue(String name) {
return given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateQueue")
.formParam("QueueName", name)
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
}
private static void subscribe(String topicArn, String protocol, String endpoint) {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Subscribe")
.formParam("TopicArn", topicArn)
.formParam("Protocol", protocol)
.formParam("Endpoint", endpoint)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<SubscriptionArn>"));
}
private static void publish(String topicArn, String message, String subject) {
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Publish")
.formParam("TopicArn", topicArn)
.formParam("Message", message);
if (subject != null) {
request.formParam("Subject", subject);
}
request.when().post("/").then().statusCode(200);
}
private static String receiveBody(String queueUrl) {
return given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ReceiveMessage")
.formParam("QueueUrl", queueUrl)
.formParam("MaxNumberOfMessages", "1")
.formParam("WaitTimeSeconds", "2")
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getString("ReceiveMessageResponse.ReceiveMessageResult.Message.Body");
}
}
@@ -0,0 +1,205 @@
package io.github.hectorvent.floci.services.sns;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.sns.model.SnsSigningKey;
import io.github.hectorvent.floci.services.sns.model.Topic;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
class SnsMessageSignerTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final String BASE_URL = "http://localhost:4566";
private static final ObjectMapper MAPPER = new ObjectMapper();
@Test
void lambdaRecord_isSignedAndVerifiesAgainstServedCertificate() throws Exception {
SnsMessageSigner signer = newSigner(AccountAwareStorageBackend.inMemory(ACCOUNT));
LambdaService lambdaService = mock(LambdaService.class);
SnsService service = new SnsService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new RegionResolver(REGION, ACCOUNT), null, lambdaService, null, BASE_URL, MAPPER, signer);
Topic topic = service.createTopic("signed-lambda-topic", null, null, REGION);
String functionArn = "arn:aws:lambda:us-east-1:000000000000:function:signed";
service.subscribe(topic.getTopicArn(), "lambda", functionArn, REGION, Map.of());
service.publish(topic.getTopicArn(), null, "hello lambda", null, REGION);
ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
verify(lambdaService).invoke(eq(REGION), eq(functionArn), payload.capture(), eq(InvocationType.Event));
JsonNode sns = MAPPER.readTree(payload.getValue()).get("Records").get(0).get("Sns");
assertEquals("1", sns.get("SignatureVersion").asText());
assertTrue(sns.get("Subject").isNull());
assertEquals(signer.certificateUrl(), sns.get("SigningCertUrl").asText());
assertTrue(sns.get("UnsubscribeUrl").asText().startsWith(BASE_URL + "/?Action=Unsubscribe&SubscriptionArn="));
assertTrue(verifies(signer, sns, "SigningCertUrl", "SHA1withRSA"));
}
@Test
void signingFailure_doesNotDeliverAnUnsignedPlaceholder() {
SnsMessageSigner signer = mock(SnsMessageSigner.class);
doThrow(new IllegalStateException("Failed to sign SNS message"))
.when(signer).sign(any(ObjectNode.class), anyString(), anyString());
LambdaService lambdaService = mock(LambdaService.class);
SnsService service = new SnsService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new RegionResolver(REGION, ACCOUNT), null, lambdaService, null, BASE_URL, MAPPER, signer);
Topic topic = service.createTopic("unsigned-lambda-topic", null, null, REGION);
String functionArn = "arn:aws:lambda:us-east-1:000000000000:function:unsigned";
service.subscribe(topic.getTopicArn(), "lambda", functionArn, REGION, Map.of());
service.publish(topic.getTopicArn(), null, "hello lambda", null, REGION);
verify(lambdaService, never()).invoke(anyString(), anyString(), any(byte[].class), any(InvocationType.class));
}
@Test
void reset_generatesANewKeyInsteadOfRestoringTheOldOne() {
AccountAwareStorageBackend<SnsSigningKey> store = AccountAwareStorageBackend.inMemory(ACCOUNT);
SnsMessageSigner signer = newSigner(store);
String before = signer.certificateUrl();
store.clear();
signer.clear();
String after = signer.certificateUrl();
assertNotEquals(before, after);
assertEquals(after, newSigner(store).certificateUrl());
}
@Test
void notificationCanonicalString_includesSubjectOnlyWhenPresent() {
ObjectNode node = MAPPER.createObjectNode();
node.put("Type", "Notification");
node.put("MessageId", "id-1");
node.put("TopicArn", "arn:aws:sns:us-east-1:000000000000:t");
node.putNull("Subject");
node.put("Message", "body");
node.put("Timestamp", "2026-10-06T00:00:00.000Z");
assertEquals("Message\nbody\nMessageId\nid-1\nTimestamp\n2026-10-06T00:00:00.000Z\n"
+ "TopicArn\narn:aws:sns:us-east-1:000000000000:t\nType\nNotification\n",
SnsMessageSigner.canonicalString(node));
node.put("Subject", "s");
assertTrue(SnsMessageSigner.canonicalString(node).contains("MessageId\nid-1\nSubject\ns\nTimestamp\n"));
}
@Test
void confirmationCanonicalString_usesSubscribeUrlAndToken() {
ObjectNode node = MAPPER.createObjectNode();
node.put("Type", "SubscriptionConfirmation");
node.put("MessageId", "id-2");
node.put("Token", "tok");
node.put("TopicArn", "arn:aws:sns:us-east-1:000000000000:t");
node.put("Message", "confirm");
node.put("SubscribeURL", "http://localhost:4566/?Action=ConfirmSubscription");
node.put("Timestamp", "2026-10-06T00:00:00.000Z");
assertEquals("Message\nconfirm\nMessageId\nid-2\n"
+ "SubscribeURL\nhttp://localhost:4566/?Action=ConfirmSubscription\n"
+ "Timestamp\n2026-10-06T00:00:00.000Z\nToken\ntok\n"
+ "TopicArn\narn:aws:sns:us-east-1:000000000000:t\nType\nSubscriptionConfirmation\n",
SnsMessageSigner.canonicalString(node));
}
@Test
void signatureVersion2_signsWithSha256AndTamperingFails() throws Exception {
SnsMessageSigner signer = newSigner(AccountAwareStorageBackend.inMemory(ACCOUNT));
ObjectNode node = notification("payload");
signer.sign(node, "2", "SigningCertURL");
assertEquals("2", node.get("SignatureVersion").asText());
assertTrue(verifies(signer, node, "SigningCertURL", "SHA256withRSA"));
assertFalse(verifies(signer, node, "SigningCertURL", "SHA1withRSA"));
node.put("Message", "forged");
assertFalse(verifies(signer, node, "SigningCertURL", "SHA256withRSA"));
}
@Test
void storedKey_isReusedAndANewKeyGetsANewUrl() {
AccountAwareStorageBackend<SnsSigningKey> store = AccountAwareStorageBackend.inMemory(ACCOUNT);
String first = newSigner(store).certificateUrl();
String restarted = newSigner(store).certificateUrl();
String fresh = newSigner(AccountAwareStorageBackend.inMemory(ACCOUNT)).certificateUrl();
assertTrue(first.matches("http://localhost:4566/_aws/sns/SimpleNotificationService-[0-9a-f]{32}\\.pem"), first);
assertEquals(first, restarted);
assertNotEquals(first, fresh);
}
@Test
void certificatePem_onlyForTheCurrentFileName() {
SnsMessageSigner signer = newSigner(AccountAwareStorageBackend.inMemory(ACCOUNT));
String url = signer.certificateUrl();
String fileName = url.substring(url.lastIndexOf('/') + 1);
assertTrue(signer.certificatePem(fileName).orElseThrow().startsWith("-----BEGIN CERTIFICATE-----"));
assertTrue(signer.certificatePem("SimpleNotificationService-0.pem").isEmpty());
}
private static SnsMessageSigner newSigner(AccountAwareStorageBackend<SnsSigningKey> store) {
return new SnsMessageSigner(store, ACCOUNT, new CertificateGenerator(), BASE_URL);
}
private static ObjectNode notification(String message) {
ObjectNode node = MAPPER.createObjectNode();
node.put("Type", "Notification");
node.put("MessageId", "6f1b4bb4-6c0c-4d6f-9d64-6d5b4d4d4d4d");
node.put("TopicArn", "arn:aws:sns:us-east-1:000000000000:signed");
node.put("Timestamp", "2026-10-06T10:00:00.000Z");
node.put("Message", message);
return node;
}
private static boolean verifies(SnsMessageSigner signer, JsonNode message, String certUrlField,
String algorithm) throws Exception {
String url = message.get(certUrlField).asText();
String pem = signer.certificatePem(url.substring(url.lastIndexOf('/') + 1)).orElseThrow();
X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509")
.generateCertificate(new ByteArrayInputStream(pem.getBytes(StandardCharsets.US_ASCII)));
String type = message.get("Type").asText();
String[] fields = "Notification".equals(type)
? new String[] {"Message", "MessageId", "Subject", "Timestamp", "TopicArn", "Type"}
: new String[] {"Message", "MessageId", "SubscribeURL", "Timestamp", "Token", "TopicArn", "Type"};
StringBuilder canonical = new StringBuilder();
for (String field : fields) {
JsonNode value = message.get(field);
if (value != null && !value.isNull()) {
canonical.append(field).append('\n').append(value.asText()).append('\n');
}
}
Signature verifier = Signature.getInstance(algorithm);
verifier.initVerify(certificate.getPublicKey());
verifier.update(canonical.toString().getBytes(StandardCharsets.UTF_8));
return verifier.verify(Base64.getDecoder().decode(message.get("Signature").asText()));
}
}