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

@@ -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; }
}