Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Rafael Almonte86dc64fc7e61
diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java
index 86e7aee43c..ac20180ba1 100644
--- a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java
@@ -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;
diff --git a/src/test/java/io/github/hectorvent/floci/services/sns/SnsHttpDeliveryIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/sns/SnsHttpDeliveryIntegrationTest.java
new file mode 100644
index 0000000000..0996b1d09c
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/sns/SnsHttpDeliveryIntegrationTest.java
@@ -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));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java
index b4d8ad3694..1c78e04671 100644
--- a/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java
@@ -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) {