feat(sns): implement HTTP/HTTPS endpoint delivery (#841) (#865)

* feat(sns): implement HTTP/HTTPS endpoint delivery (#841)

Add HTTP/HTTPS webhook delivery to SNS topics. When a message is
  published to a topic with HTTP(S) subscribers, a POST is now made to
  the endpoint with the SNS notification envelope and standard headers.

* fix(sns): address review feedback for HTTP/HTTPS delivery

- Use proper SubscriptionConfirmation flow instead of auto-confirm
- Make HTTP delivery async with sendAsync to avoid blocking Publish
- Log non-2xx responses as warnings instead of successful deliveries
- Fix field name SigningCertUrl -> SigningCertURL for HTTP notifications
- Add x-amz-sns-rawdelivery header for raw message delivery
- Validate endpoint scheme matches protocol on subscribe
- Use BodyHandlers.discarding() since response body is unused
- Pass null HttpClient in test constructor to avoid real connections
- Add message attributes coverage to integration test

* fix(sns): correct subscription-arn header and binary attribute serialization

  - Send PendingConfirmation as x-amz-sns-subscription-arn header in
    SubscriptionConfirmation requests, matching AWS wire protocol
  - Base64-encode binary MessageAttributes in HTTP notification envelope
    instead of producing null
  - Add header assertion to subscription confirmation integration test
This commit is contained in:
Rafael Almonte authored and GitHub committed 2026-05-18 18:58:09 -05:00
1 parent c36fa99a95
commit 86dc64fc7e
3 files changed
+522 -3

No files matched your search

@@ -21,6 +21,10 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.math.BigDecimal;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -52,6 +56,7 @@ public class SnsService {
private final LambdaService lambdaService;
private final String baseUrl;
private final ObjectMapper objectMapper;
private final HttpClient httpClient;
private final Map<String, Instant> fifoDeduplicationCache = new ConcurrentHashMap<>();
private static final HexFormat HEX = HexFormat.of();
@@ -75,14 +80,20 @@ public class SnsService {
}
/**
* Package-private constructor for testing.
* Package-private constructor for testing (no HTTP client — HTTP delivery is skipped).
*/
SnsService(StorageBackend<String, Topic> topicStore,
StorageBackend<String, Subscription> subscriptionStore,
RegionResolver regionResolver, SqsService sqsService,
LambdaService lambdaService) {
this(topicStore, subscriptionStore, regionResolver, sqsService, lambdaService, "http://localhost:4566",
new ObjectMapper());
this.topicStore = topicStore;
this.subscriptionStore = subscriptionStore;
this.regionResolver = regionResolver;
this.sqsService = sqsService;
this.lambdaService = lambdaService;
this.baseUrl = "http://localhost:4566";
this.objectMapper = new ObjectMapper();
this.httpClient = null;
}
SnsService(StorageBackend<String, Topic> topicStore,
@@ -96,6 +107,7 @@ public class SnsService {
this.lambdaService = lambdaService;
this.baseUrl = baseUrl;
this.objectMapper = objectMapper;
this.httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
}
public Topic createTopic(String name, Map<String, String> attributes,
@@ -190,6 +202,11 @@ public class SnsService {
if (protocol == null || protocol.isBlank()) {
throw new AwsException("InvalidParameter", "Protocol is required.", 400);
}
if (("http".equals(protocol) && endpoint != null && !endpoint.startsWith("http://"))
|| ("https".equals(protocol) && endpoint != null && !endpoint.startsWith("https://"))) {
throw new AwsException("InvalidParameter",
"Invalid parameter: Endpoint scheme does not match protocol '" + protocol + "'.", 400);
}
for (Subscription existing : subscriptionsByTopic(topicArn, region)) {
if (protocol.equals(existing.getProtocol())
@@ -219,6 +236,11 @@ public class SnsService {
} else {
LOG.infov("Subscribed {0} ({1}) to topic {2} in {3} with attributes: {4}", endpoint, protocol, topicArn, region, attributes);
}
if (("http".equals(protocol) || "https".equals(protocol)) && endpoint != null) {
sendSubscriptionConfirmation(subscription, topicArn, region);
}
return subscription;
}
@@ -866,6 +888,31 @@ public class SnsService {
lambdaService.invoke(region, fnName, eventJson.getBytes(), InvocationType.Event);
LOG.debugv("Delivered SNS message to Lambda: {0}", sub.getEndpoint());
}
case "http", "https" -> {
if (httpClient == null) break;
boolean rawDelivery = "true".equalsIgnoreCase(sub.getAttributes().get("RawMessageDelivery"));
String body = rawDelivery
? message
: buildSnsHttpNotification(message, subject, messageAttributes, topicArn, messageId, sub.getSubscriptionArn());
var requestBuilder = HttpRequest.newBuilder()
.uri(URI.create(sub.getEndpoint()))
.timeout(Duration.ofSeconds(5))
.header("Content-Type", "text/plain; charset=UTF-8")
.header("x-amz-sns-message-type", "Notification")
.header("x-amz-sns-message-id", messageId)
.header("x-amz-sns-topic-arn", topicArn)
.header("x-amz-sns-subscription-arn", sub.getSubscriptionArn());
if (rawDelivery) {
requestBuilder.header("x-amz-sns-rawdelivery", "true");
}
HttpRequest request = requestBuilder
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
String endpoint = sub.getEndpoint();
httpClient.sendAsync(request, HttpResponse.BodyHandlers.discarding())
.thenAccept(response -> logHttpResult("Delivered SNS notification", endpoint, response.statusCode()))
.exceptionally(ex -> { LOG.warnv("Failed to deliver SNS message to {0}: {1}", endpoint, ex.getMessage()); return null; });
}
case "email", "email-json" -> LOG.infov("SNS email delivery (stub): to={0}, subject={1}, message={2}",
sub.getEndpoint(), subject, message);
case "sms" -> LOG.infov("SNS SMS delivery (stub): to={0}, message={1}", sub.getEndpoint(), message);
@@ -967,6 +1014,88 @@ public class SnsService {
}
}
private String buildSnsHttpNotification(String message, String subject,
Map<String, MessageAttributeValue> messageAttributes,
String topicArn, String messageId, String subscriptionArn) {
try {
String timestamp = DateTimeFormatter.ISO_INSTANT.format(Instant.now());
ObjectNode node = objectMapper.createObjectNode();
node.put("Type", "Notification");
node.put("MessageId", messageId);
node.put("TopicArn", topicArn);
node.put("Timestamp", timestamp);
if (subject != null) {
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);
ObjectNode attrs = node.putObject("MessageAttributes");
if (messageAttributes != null) {
for (var entry : messageAttributes.entrySet()) {
ObjectNode attr = attrs.putObject(entry.getKey());
attr.put("Type", entry.getValue().getDataType());
if (entry.getValue().getBinaryValue() != null) {
attr.put("Value", java.util.Base64.getEncoder()
.encodeToString(entry.getValue().getBinaryValue()));
} else {
attr.put("Value", entry.getValue().getStringValue());
}
}
}
return objectMapper.writeValueAsString(node);
} catch (Exception e) {
return "{}";
}
}
private void logHttpResult(String action, String endpoint, int statusCode) {
if (statusCode >= 200 && statusCode < 300) {
LOG.debugv("{0} to {1}, status={2}", action, endpoint, statusCode);
} else {
LOG.warnv("{0} to {1} returned non-success status {2}", action, endpoint, statusCode);
}
}
private void sendSubscriptionConfirmation(Subscription subscription, String topicArn, String region) {
if (httpClient == null) return;
try {
String token = subscription.getAttributes().get("ConfirmationToken");
String subscribeUrl = baseUrl + "/?Action=ConfirmSubscription&TopicArn=" + topicArn + "&Token=" + token;
String timestamp = DateTimeFormatter.ISO_INSTANT.format(Instant.now());
ObjectNode node = objectMapper.createObjectNode();
node.put("Type", "SubscriptionConfirmation");
node.put("MessageId", UUID.randomUUID().toString());
node.put("TopicArn", topicArn);
node.put("Timestamp", timestamp);
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");
String body = objectMapper.writeValueAsString(node);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(subscription.getEndpoint()))
.timeout(Duration.ofSeconds(5))
.header("Content-Type", "text/plain; charset=UTF-8")
.header("x-amz-sns-message-type", "SubscriptionConfirmation")
.header("x-amz-sns-topic-arn", topicArn)
.header("x-amz-sns-subscription-arn", "PendingConfirmation")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
String endpoint = subscription.getEndpoint();
httpClient.sendAsync(request, HttpResponse.BodyHandlers.discarding())
.thenAccept(response -> logHttpResult("Sent SubscriptionConfirmation", endpoint, response.statusCode()))
.exceptionally(ex -> { LOG.warnv("Failed to send SubscriptionConfirmation to {0}: {1}", endpoint, ex.getMessage()); return null; });
} catch (Exception e) {
LOG.warnv("Failed to send SubscriptionConfirmation to {0}: {1}", subscription.getEndpoint(), e.getMessage());
}
}
private String sqsArnToUrl(String arn) {
if (arn == null) return null;
if (arn.startsWith("http")) return arn;