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

@@ -0,0 +1,347 @@
package io.github.hectorvent.floci.services.sns;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpServer;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.*;
/**
* Integration tests for SNS HTTP/HTTPS endpoint delivery.
* Uses an embedded HTTP server to receive webhook POSTs.
*/
@QuarkusTest
class SnsHttpDeliveryIntegrationTest {
private static HttpServer httpServer;
private static int httpPort;
private static final List<ReceivedRequest> receivedRequests = new CopyOnWriteArrayList<>();
private static final ObjectMapper objectMapper = new ObjectMapper();
record ReceivedRequest(String body, Map<String, List<String>> headers) {}
@BeforeAll
static void startHttpServer() throws IOException {
httpServer = HttpServer.create(new InetSocketAddress(0), 0);
httpPort = httpServer.getAddress().getPort();
httpServer.createContext("/webhook", exchange -> {
byte[] bodyBytes = exchange.getRequestBody().readAllBytes();
String body = new String(bodyBytes, StandardCharsets.UTF_8);
Map<String, List<String>> headers = exchange.getRequestHeaders();
receivedRequests.add(new ReceivedRequest(body, headers));
exchange.sendResponseHeaders(200, 0);
exchange.close();
});
httpServer.start();
}
@AfterAll
static void stopHttpServer() {
if (httpServer != null) {
httpServer.stop(0);
}
}
/**
* Waits until the expected number of requests have been received, with a timeout.
*/
private static void awaitRequests(int expectedCount) throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (receivedRequests.size() < expectedCount && System.nanoTime() < deadline) {
Thread.sleep(50);
}
}
/**
* Extracts the Token and TopicArn from the SubscriptionConfirmation message
* and calls ConfirmSubscription via POST (matching how the SDK confirms).
*/
private static void confirmSubscription(ReceivedRequest confirmationRequest) throws Exception {
JsonNode node = objectMapper.readTree(confirmationRequest.body());
assertEquals("SubscriptionConfirmation", node.get("Type").asText());
String token = node.get("Token").asText();
String topicArn = node.get("TopicArn").asText();
assertNotNull(token);
assertNotNull(topicArn);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ConfirmSubscription")
.formParam("TopicArn", topicArn)
.formParam("Token", token)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<SubscriptionArn>"));
}
@Test
void publish_toHttpSubscriber_deliversNotificationEnvelope() throws Exception {
receivedRequests.clear();
String endpoint = "http://localhost:" + httpPort + "/webhook";
// Create topic
String topicArn = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateTopic")
.formParam("Name", "http-delivery-test")
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");
// Subscribe HTTP endpoint — this sends SubscriptionConfirmation to the endpoint
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Subscribe")
.formParam("TopicArn", topicArn)
.formParam("Protocol", "http")
.formParam("Endpoint", endpoint)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<SubscriptionArn>"));
// The webhook should have received the SubscriptionConfirmation
awaitRequests(1);
assertEquals(1, receivedRequests.size());
ReceivedRequest confirmReq = receivedRequests.get(0);
assertEquals("SubscriptionConfirmation", confirmReq.headers().get("X-amz-sns-message-type").get(0));
// Confirm the subscription
confirmSubscription(confirmReq);
receivedRequests.clear();
// Publish message with message attributes
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Publish")
.formParam("TopicArn", topicArn)
.formParam("Message", "Hello HTTP endpoint!")
.formParam("Subject", "Test Subject")
.formParam("MessageAttributes.entry.1.Name", "env")
.formParam("MessageAttributes.entry.1.Value.DataType", "String")
.formParam("MessageAttributes.entry.1.Value.StringValue", "production")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<MessageId>"));
// Verify webhook received the notification POST
awaitRequests(1);
assertEquals(1, receivedRequests.size());
ReceivedRequest req = receivedRequests.get(0);
// Verify SNS headers
assertNotNull(req.headers().get("X-amz-sns-message-type"));
assertEquals("Notification", req.headers().get("X-amz-sns-message-type").get(0));
assertNotNull(req.headers().get("X-amz-sns-topic-arn"));
assertEquals(topicArn, req.headers().get("X-amz-sns-topic-arn").get(0));
assertNotNull(req.headers().get("X-amz-sns-message-id"));
assertNotNull(req.headers().get("X-amz-sns-subscription-arn"));
// Verify body is a proper SNS notification envelope
JsonNode envelope = objectMapper.readTree(req.body());
assertEquals("Notification", envelope.get("Type").asText());
assertEquals(topicArn, envelope.get("TopicArn").asText());
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());
assertTrue(envelope.get("UnsubscribeURL").asText().contains("Action=Unsubscribe"));
assertNotNull(envelope.get("MessageId").asText());
assertNotNull(envelope.get("Timestamp").asText());
// Verify message attributes in envelope
JsonNode msgAttrs = envelope.get("MessageAttributes");
assertNotNull(msgAttrs);
assertTrue(msgAttrs.has("env"));
assertEquals("String", msgAttrs.get("env").get("Type").asText());
assertEquals("production", msgAttrs.get("env").get("Value").asText());
}
@Test
void publish_toHttpSubscriber_rawMessageDelivery() throws Exception {
receivedRequests.clear();
String endpoint = "http://localhost:" + httpPort + "/webhook";
// Create topic
String topicArn = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateTopic")
.formParam("Name", "http-raw-delivery-test")
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");
// Subscribe HTTP endpoint
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Subscribe")
.formParam("TopicArn", topicArn)
.formParam("Protocol", "http")
.formParam("Endpoint", endpoint)
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getString("SubscribeResponse.SubscribeResult.SubscriptionArn");
// Confirm subscription
awaitRequests(1);
assertEquals(1, receivedRequests.size());
confirmSubscription(receivedRequests.get(0));
receivedRequests.clear();
// Get the subscription ARN to set attributes
String subscriptionArn = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListSubscriptionsByTopic")
.formParam("TopicArn", topicArn)
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getString("**.find { it.Protocol == 'http' }.SubscriptionArn");
// Set RawMessageDelivery attribute
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SetSubscriptionAttributes")
.formParam("SubscriptionArn", subscriptionArn)
.formParam("AttributeName", "RawMessageDelivery")
.formParam("AttributeValue", "true")
.when()
.post("/")
.then()
.statusCode(200);
// Publish message
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Publish")
.formParam("TopicArn", topicArn)
.formParam("Message", "Raw message body")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<MessageId>"));
// Verify webhook received raw message
awaitRequests(1);
assertEquals(1, receivedRequests.size());
ReceivedRequest req = receivedRequests.get(0);
assertEquals("Raw message body", req.body());
// SNS headers should still be present
assertNotNull(req.headers().get("X-amz-sns-message-type"));
assertEquals("Notification", req.headers().get("X-amz-sns-message-type").get(0));
// Raw delivery marker header
assertNotNull(req.headers().get("X-amz-sns-rawdelivery"));
assertEquals("true", req.headers().get("X-amz-sns-rawdelivery").get(0));
}
@Test
void publish_toUnreachableHttpEndpoint_doesNotFail() {
// Subscribe to unreachable endpoint — SubscriptionConfirmation will fail but that's OK
String topicArn = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateTopic")
.formParam("Name", "http-unreachable-test")
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Subscribe")
.formParam("TopicArn", topicArn)
.formParam("Protocol", "http")
.formParam("Endpoint", "http://localhost:1/unreachable")
.when()
.post("/")
.then()
.statusCode(200);
// Publish should still succeed (subscription is pending so delivery is skipped)
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Publish")
.formParam("TopicArn", topicArn)
.formParam("Message", "This will not be delivered because subscription is unconfirmed")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<MessageId>"));
}
@Test
void subscribe_sendsSubscriptionConfirmation_withCorrectFields() throws Exception {
receivedRequests.clear();
String endpoint = "http://localhost:" + httpPort + "/webhook";
String topicArn = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateTopic")
.formParam("Name", "http-confirm-fields-test")
.when()
.post("/")
.then()
.statusCode(200)
.extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "Subscribe")
.formParam("TopicArn", topicArn)
.formParam("Protocol", "http")
.formParam("Endpoint", endpoint)
.when()
.post("/")
.then()
.statusCode(200);
// Verify SubscriptionConfirmation message fields
awaitRequests(1);
assertEquals(1, receivedRequests.size());
ReceivedRequest req = receivedRequests.get(0);
JsonNode body = objectMapper.readTree(req.body());
assertEquals("SubscriptionConfirmation", body.get("Type").asText());
assertEquals(topicArn, body.get("TopicArn").asText());
assertNotNull(body.get("Token").asText());
assertFalse(body.get("Token").asText().isBlank());
assertTrue(body.get("SubscribeURL").asText().contains("Action=ConfirmSubscription"));
assertTrue(body.get("SubscribeURL").asText().contains("Token="));
assertEquals("1", body.get("SignatureVersion").asText());
assertNotNull(body.get("MessageId").asText());
assertNotNull(body.get("Timestamp").asText());
// Subscription ARN header must be "PendingConfirmation" for confirmation requests
assertNotNull(req.headers().get("X-amz-sns-subscription-arn"));
assertEquals("PendingConfirmation", req.headers().get("X-amz-sns-subscription-arn").get(0));
}
}
@@ -266,6 +266,49 @@ class SnsServiceTest {
assertEquals("2", attrs.get("SubscriptionsConfirmed"));
}
@Test
void publish_withHttpSubscriber_pendingConfirmation_skipsDelivery() {
Topic topic = snsService.createTopic("http-topic", null, null, REGION);
Subscription sub = snsService.subscribe(topic.getTopicArn(), "http",
"http://localhost:9999/webhook", REGION, Map.of());
// HTTP subscription should be pending confirmation
assertEquals("true", sub.getAttributes().get("PendingConfirmation"));
assertNotNull(sub.getAttributes().get("ConfirmationToken"));
// Publish should succeed but skip delivery to pending subscription
String messageId = snsService.publish(topic.getTopicArn(), null, "Hello HTTP!", null, REGION);
assertNotNull(messageId);
}
@Test
void subscribe_httpPendingConfirmation_canBeConfirmed() {
Topic topic = snsService.createTopic("http-topic2", null, null, REGION);
Subscription sub = snsService.subscribe(topic.getTopicArn(), "http",
"http://localhost:9999/webhook", REGION, Map.of());
assertEquals("true", sub.getAttributes().get("PendingConfirmation"));
String token = sub.getAttributes().get("ConfirmationToken");
assertNotNull(token);
// Confirm the subscription
String confirmedArn = snsService.confirmSubscription(topic.getTopicArn(), token, REGION);
assertEquals(sub.getSubscriptionArn(), confirmedArn);
}
@Test
void subscribe_httpProtocol_rejectsHttpsEndpoint() {
Topic topic = snsService.createTopic("scheme-topic", null, null, REGION);
assertThrows(AwsException.class,
() -> snsService.subscribe(topic.getTopicArn(), "http",
"https://example.com/hook", REGION, Map.of()));
}
@Test
void subscribe_httpsProtocol_rejectsHttpEndpoint() {
Topic topic = snsService.createTopic("scheme-topic2", null, null, REGION);
assertThrows(AwsException.class,
() -> snsService.subscribe(topic.getTopicArn(), "https",
"http://example.com/hook", REGION, Map.of()));
}
private static final ObjectMapper MAPPER = new ObjectMapper();
private Subscription subscriptionWithPolicy(String filterPolicy, String scope) {