Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(sns): deliver topic broadcasts to application-protocol platform endpoints (#1856)

Abhigyaf45d64a00e70
diff --git a/docs/services/sns.md b/docs/services/sns.md
index 4f0f0a560e..6d08f49a02 100644
--- a/docs/services/sns.md
+++ b/docs/services/sns.md
@@ -86,6 +86,7 @@ Supported subscription protocols:
- `sqs` — delivers to a Floci SQS queue
- `lambda` — invokes a Floci Lambda function
- `http` / `https` — posts to an HTTP endpoint
+- `application` — fans out to a mobile push platform endpoint (see [Mobile push](#mobile-push-mock))
## Mobile push (mock)
@@ -122,6 +123,42 @@ When `MessageStructure="json"`, Floci picks the key matching the endpoint's plat
(`APNS`, `APNS_SANDBOX`, `GCM`, or `FCM`), falling back to `default`. The envelope
must be a JSON object and must include `default` — otherwise `InvalidParameter`.
+### Broadcast to devices via a topic
+
+Subscribe platform endpoints to a topic with `Protocol="application"`, then publish to
+the topic to fan out to every subscribed device — each endpoint is captured exactly as
+if you had published to it directly (same platform-payload resolution, same `Enabled`
+gating). A disabled endpoint in the fan-out is skipped; the rest still receive the push.
+
+```bash
+aws sns subscribe --topic-arn $TOPIC_ARN \
+ --protocol application --notification-endpoint $ENDPOINT_ARN \
+ --endpoint-url http://localhost:4566
+
+aws sns publish --topic-arn $TOPIC_ARN --message-structure json \
+ --message '{"default":"market open","GCM":"{\"notification\":{\"body\":\"market alert\"}}"}' \
+ --endpoint-url http://localhost:4566
+```
+
+Broadcast pushes surface in the same retrospection API, keyed by `EndpointArn`.
+
+### Per-protocol payloads on topic publish
+
+`MessageStructure="json"` resolves per subscriber, not just for mobile endpoints. Each
+subscription receives the value under its own protocol key — `sqs`, `lambda`, `http`,
+`https`, `email`, `email-json`, `sms`, or the push platform (`APNS`, `GCM`, …) for
+`application` — falling back to `default` when that key is absent.
+
+```bash
+aws sns publish --topic-arn $TOPIC_ARN --message-structure json \
+ --message '{"default":"hello","sqs":"hi sqs","GCM":"{\"notification\":{\"body\":\"hi device\"}}"}' \
+ --endpoint-url http://localhost:4566
+```
+
+The SQS subscriber receives `hi sqs`, the platform endpoint receives the `GCM` payload,
+and every other subscriber receives `hello`. As with any topic publish, the envelope must
+be a JSON object carrying `default`, validated before fan-out begins.
+
### Inspecting captured pushes
```bash
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 fdb1ff1043..db7af234f2 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
@@ -404,6 +404,8 @@ public class SnsService implements Resettable {
Topic topic = topicStore.get(topicStoreKey)
.orElseThrow(() -> new AwsException("NotFound", "Topic does not exist.", 404));
+ validateTopicMessageStructure(message, messageStructure);
+
boolean isFifo = "true".equals(topic.getAttributes().get("FifoTopic"));
String dedupId = messageDeduplicationId;
if (isFifo) {
@@ -435,7 +437,7 @@ public class SnsService implements Resettable {
if (!matchesFilterPolicy(sub, parsedBody, messageAttributes)) {
continue;
}
- deliverMessage(sub, message, subject, messageAttributes, messageId, effectiveArn, messageGroupId, dedupId);
+ deliverMessage(sub, message, subject, messageAttributes, messageId, effectiveArn, messageGroupId, dedupId, messageStructure);
}
LOG.infov("Published message {0} to topic {1}", messageId, effectiveArn);
return messageId;
@@ -629,7 +631,18 @@ public class SnsService implements Resettable {
throw new AwsException("PlatformApplicationDisabled",
"Platform application is disabled.", 400);
}
- String payload = resolvePushPayload(app.getPlatform(), message, messageStructure);
+ return capturePushForEndpoint(endpoint, app, message, subject, messageStructure, messageAttributes);
+ }
+
+ /**
+ * Resolves the platform payload and records a captured push for the given endpoint/app.
+ * Shared by direct-to-endpoint {@code Publish} and topic fan-out to {@code application}
+ * subscriptions, so broadcast pushes surface identically via the retrospection API.
+ */
+ private String capturePushForEndpoint(PlatformEndpoint endpoint, PlatformApplication app,
+ String message, String subject, String messageStructure,
+ Map<String, MessageAttributeValue> messageAttributes) {
+ String payload = resolveProtocolPayload(app.getPlatform(), message, messageStructure);
String messageId = UUID.randomUUID().toString();
recordPushNotification(new PushNotification(
endpoint.getArn(), app.getArn(), app.getPlatform(), endpoint.getToken(),
@@ -639,12 +652,15 @@ public class SnsService implements Resettable {
}
/**
- * Resolves the payload SNS would forward to APNS/FCM for this platform.
- * If {@code messageStructure="json"}, pick the platform-specific key ({@code APNS},
- * {@code APNS_SANDBOX}, {@code GCM}, {@code FCM}) from the JSON envelope, falling back
- * to {@code default}. Otherwise return the raw message.
+ * Resolves the payload SNS would forward to a given delivery target.
+ * If {@code messageStructure="json"}, pick the target-specific key from the JSON envelope,
+ * falling back to {@code default}. The key is the push platform for mobile endpoints
+ * ({@code APNS}, {@code APNS_SANDBOX}, {@code GCM}, {@code FCM}) and the subscription
+ * protocol for every other subscriber ({@code sqs}, {@code lambda}, {@code http},
+ * {@code https}, {@code email}, {@code email-json}, {@code sms}).
+ * Otherwise return the raw message.
*/
- private String resolvePushPayload(String platform, String message, String messageStructure) {
+ private String resolveProtocolPayload(String protocol, String message, String messageStructure) {
if (messageStructure == null || !"json".equals(messageStructure)) {
return message;
}
@@ -660,20 +676,53 @@ public class SnsService implements Resettable {
"Invalid parameter: Message Reason: Messages must be a JSON object.",
400);
}
- JsonNode platformValue = root.get(platform);
- if (platformValue != null && !platformValue.isNull()) {
- return platformValue.isTextual() ? platformValue.asText() : platformValue.toString();
+ // Real SNS ignores a key whose value isn't a string ("Non-string values will cause the
+ // key to be ignored"), falling through to default rather than stringifying it.
+ JsonNode protocolValue = root.get(protocol);
+ if (protocolValue != null && protocolValue.isTextual()) {
+ return protocolValue.asText();
}
JsonNode defaultValue = root.get("default");
- if (defaultValue != null && !defaultValue.isNull()) {
- return defaultValue.isTextual() ? defaultValue.asText() : defaultValue.toString();
+ if (defaultValue != null && defaultValue.isTextual()) {
+ return defaultValue.asText();
}
throw new AwsException("InvalidParameter",
- "Invalid parameter: Message Reason: Messages must have a '" + platform
+ "Invalid parameter: Message Reason: Messages must have a '" + protocol
+ "' or 'default' key.",
400);
}
+ /**
+ * Validates {@code MessageStructure="json"} on a topic {@code Publish} the way the real SNS
+ * API does: synchronously, before any fan-out. The message must be a JSON object carrying a
+ * top-level {@code default} entry. Validating here (rather than lazily inside per-subscriber
+ * delivery) means a malformed envelope surfaces to the caller as {@code InvalidParameter}
+ * instead of being silently swallowed while the {@code publish} call still reports success.
+ * {@code PublishBatch} runs the same check per entry, reporting a bad envelope as that entry's
+ * {@code BatchResultErrorEntry} rather than failing the whole batch.
+ */
+ private void validateTopicMessageStructure(String message, String messageStructure) {
+ if (!"json".equals(messageStructure)) {
+ return;
+ }
+ JsonNode root;
+ try {
+ root = objectMapper.readTree(message);
+ } catch (Exception e) {
+ throw new AwsException("InvalidParameter",
+ "Invalid parameter: Message Structure - JSON message body failed to parse", 400);
+ }
+ if (root == null || !root.isObject()) {
+ throw new AwsException("InvalidParameter",
+ "Invalid parameter: Message Structure - JSON message body should be an object.", 400);
+ }
+ JsonNode defaultValue = root.get("default");
+ if (defaultValue == null || !defaultValue.isTextual()) {
+ throw new AwsException("InvalidParameter",
+ "Invalid parameter: Message Structure - No default entry in JSON message body", 400);
+ }
+ }
+
private void recordPushNotification(PushNotification notification) {
pushCapture.addFirst(notification);
while (pushCapture.size() > PUSH_CAPTURE_LIMIT) {
@@ -783,9 +832,17 @@ public class SnsService implements Resettable {
continue;
}
String subject = (String) entry.get("Subject");
+ String messageStructure = (String) entry.get("MessageStructure");
String messageGroupId = (String) entry.get("MessageGroupId");
String messageDeduplicationId = (String) entry.get("MessageDeduplicationId");
+ try {
+ validateTopicMessageStructure(message, messageStructure);
+ } catch (AwsException e) {
+ failed.add(new String[]{id, e.getErrorCode(), e.getMessage(), "true"});
+ continue;
+ }
+
if (isFifo && (messageGroupId == null || messageGroupId.isBlank())) {
failed.add(new String[]{id, "InvalidParameter",
"MessageGroupId is required for FIFO topics.", "true"});
@@ -812,7 +869,7 @@ public class SnsService implements Resettable {
bodyParseAttempted = true;
}
if (!matchesFilterPolicy(sub, parsedBody, attrs)) continue;
- deliverMessage(sub, message, subject, attrs, messageId, topicArn, messageGroupId, messageDeduplicationId);
+ deliverMessage(sub, message, subject, attrs, messageId, topicArn, messageGroupId, messageDeduplicationId, messageStructure);
}
LOG.debugv("Batch published message {0} (id={1}) to {2}", messageId, id, topicArn);
successful.add(new String[]{id, messageId});
@@ -1228,8 +1285,15 @@ public class SnsService implements Resettable {
private void deliverMessage(Subscription sub, String message, String subject,
Map<String, MessageAttributeValue> messageAttributes, String messageId,
- String topicArn, String messageGroupId, String messageDeduplicationId) {
+ String topicArn, String messageGroupId, String messageDeduplicationId,
+ String messageStructure) {
try {
+ // Under MessageStructure="json" every subscriber gets the value under its own
+ // protocol key, falling back to "default". The application case resolves against
+ // the push platform (APNS/GCM/...) inside capturePushForEndpoint instead.
+ String protocolMessage = "application".equals(sub.getProtocol())
+ ? message
+ : resolveProtocolPayload(sub.getProtocol(), message, messageStructure);
switch (sub.getProtocol()) {
case "sqs" -> {
String region = extractRegionFromArn(sub.getEndpoint());
@@ -1239,8 +1303,8 @@ public class SnsService implements Resettable {
String queueUrl = sqsArnToUrl(sub.getEndpoint());
boolean rawDelivery = "true".equalsIgnoreCase(sub.getAttributes().get("RawMessageDelivery"));
String body = rawDelivery
- ? message
- : buildSnsEnvelope(message, subject, messageAttributes, topicArn, messageId);
+ ? protocolMessage
+ : buildSnsEnvelope(protocolMessage, subject, messageAttributes, topicArn, messageId);
Map<String, MessageAttributeValue> sqsAttributes = rawDelivery
? toSqsMessageAttributes(messageAttributes)
: Collections.emptyMap();
@@ -1250,7 +1314,7 @@ public class SnsService implements Resettable {
case "lambda" -> {
String fnName = extractFunctionName(sub.getEndpoint());
String region = extractRegionFromArn(sub.getEndpoint());
- String eventJson = buildSnsLambdaEvent(topicArn, messageId, message,
+ String eventJson = buildSnsLambdaEvent(topicArn, messageId, protocolMessage,
subject, messageAttributes, sub.getSubscriptionArn());
lambdaService.invoke(region, fnName, eventJson.getBytes(), InvocationType.Event);
LOG.debugv("Delivered SNS message to Lambda: {0}", sub.getEndpoint());
@@ -1259,8 +1323,8 @@ public class SnsService implements Resettable {
if (httpClient == null) break;
boolean rawDelivery = "true".equalsIgnoreCase(sub.getAttributes().get("RawMessageDelivery"));
String body = rawDelivery
- ? message
- : buildSnsHttpNotification(message, subject, messageAttributes, topicArn, messageId, sub.getSubscriptionArn());
+ ? protocolMessage
+ : buildSnsHttpNotification(protocolMessage, subject, messageAttributes, topicArn, messageId, sub.getSubscriptionArn());
var requestBuilder = HttpRequest.newBuilder()
.uri(URI.create(sub.getEndpoint()))
.timeout(Duration.ofSeconds(5))
@@ -1280,9 +1344,34 @@ public class SnsService implements Resettable {
.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 "application" -> {
+ String region = extractRegionFromArn(sub.getEndpoint());
+ if (region == null) {
+ region = extractRegionFromArn(topicArn);
+ }
+ String endpointArn = sub.getEndpoint();
+ PlatformEndpoint endpoint = platformEndpointStore.get(endpointKey(region, endpointArn)).orElse(null);
+ if (endpoint == null) {
+ LOG.debugv("Skipping topic fan-out to missing platform endpoint {0}", endpointArn);
+ break;
+ }
+ if (!"true".equalsIgnoreCase(endpoint.getAttributes().getOrDefault("Enabled", "true"))) {
+ LOG.debugv("Skipping topic fan-out to disabled platform endpoint {0}", endpointArn);
+ break;
+ }
+ PlatformApplication app = platformAppStore.get(
+ platformAppKey(region, endpoint.getPlatformApplicationArn())).orElse(null);
+ if (app == null || "false".equalsIgnoreCase(app.getAttributes().get("Enabled"))) {
+ LOG.debugv("Skipping topic fan-out to endpoint {0}: platform application missing or disabled",
+ endpointArn);
+ break;
+ }
+ capturePushForEndpoint(endpoint, app, message, subject, messageStructure, messageAttributes);
+ LOG.debugv("Delivered SNS message to platform endpoint: {0}", endpointArn);
+ }
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);
+ sub.getEndpoint(), subject, protocolMessage);
+ case "sms" -> LOG.infov("SNS SMS delivery (stub): to={0}, message={1}", sub.getEndpoint(), protocolMessage);
default -> LOG.debugv("Protocol {0} delivery not implemented, skipping: {1}",
sub.getProtocol(), sub.getEndpoint());
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/sns/SnsMobilePushTest.java b/src/test/java/io/github/hectorvent/floci/services/sns/SnsMobilePushTest.java
index c9fb5098e2..0752daa619 100644
--- a/src/test/java/io/github/hectorvent/floci/services/sns/SnsMobilePushTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/sns/SnsMobilePushTest.java
@@ -322,6 +322,154 @@ class SnsMobilePushTest {
assertEquals("PlatformApplicationDisabled", e.getErrorCode());
}
+ // --- Publish: topic broadcast to platform endpoints (Protocol="application") ---
+
+ @Test
+ void publish_topicBroadcastToApplicationEndpointsCapturesForEachDevice() {
+ PlatformApplication app = snsService.createPlatformApplication("android-app", "GCM", Map.of(), REGION);
+ PlatformEndpoint deviceA = snsService.createPlatformEndpoint(app.getArn(), "fcm-token-a", null, Map.of(), REGION);
+ PlatformEndpoint deviceB = snsService.createPlatformEndpoint(app.getArn(), "fcm-token-b", null, Map.of(), REGION);
+
+ String topicArn = snsService.createTopic("market-alerts", null, null, REGION).getTopicArn();
+ snsService.subscribe(topicArn, "application", deviceA.getArn(), REGION, Map.of());
+ snsService.subscribe(topicArn, "application", deviceB.getArn(), REGION, Map.of());
+
+ String envelope = "{"
+ + "\"default\":\"market open\","
+ + "\"GCM\":\"{\\\"notification\\\":{\\\"body\\\":\\\"market alert\\\"}}\""
+ + "}";
+ String messageId = snsService.publish(topicArn, null, null, envelope, null, "json",
+ null, null, null, REGION);
+ assertNotNull(messageId);
+
+ List<PushNotification> capturedA = snsService.peekPushNotifications(deviceA.getArn());
+ List<PushNotification> capturedB = snsService.peekPushNotifications(deviceB.getArn());
+ assertEquals(1, capturedA.size());
+ assertEquals(1, capturedB.size());
+ assertEquals("GCM", capturedA.get(0).platform());
+ assertEquals("fcm-token-a", capturedA.get(0).token());
+ assertEquals("fcm-token-b", capturedB.get(0).token());
+ assertTrue(capturedA.get(0).payload().contains("market alert"));
+ assertTrue(capturedB.get(0).payload().contains("market alert"));
+ }
+
+ @Test
+ void publish_topicBroadcastSkipsDisabledEndpointButDeliversToEnabled() {
+ PlatformApplication app = snsService.createPlatformApplication("android-app", "GCM", Map.of(), REGION);
+ PlatformEndpoint enabled = snsService.createPlatformEndpoint(app.getArn(), "fcm-token-live", null, Map.of(), REGION);
+ PlatformEndpoint disabled = snsService.createPlatformEndpoint(app.getArn(), "fcm-token-dead", null, Map.of(), REGION);
+ snsService.setEndpointAttributes(disabled.getArn(), Map.of("Enabled", "false"), REGION);
+
+ String topicArn = snsService.createTopic("market-alerts", null, null, REGION).getTopicArn();
+ snsService.subscribe(topicArn, "application", enabled.getArn(), REGION, Map.of());
+ snsService.subscribe(topicArn, "application", disabled.getArn(), REGION, Map.of());
+
+ assertDoesNotThrow(() -> snsService.publish(topicArn, null, null,
+ "{\"GCM\":\"hi\",\"default\":\"hi\"}", null, "json", null, null, null, REGION));
+
+ assertEquals(1, snsService.peekPushNotifications(enabled.getArn()).size());
+ assertTrue(snsService.peekPushNotifications(disabled.getArn()).isEmpty());
+ }
+
+ @Test
+ void publish_topicBroadcastFallsBackToDefaultWhenPlatformKeyMissing() {
+ PlatformApplication app = snsService.createPlatformApplication("android-app", "GCM", Map.of(), REGION);
+ PlatformEndpoint device = snsService.createPlatformEndpoint(app.getArn(), "fcm-token", null, Map.of(), REGION);
+
+ String topicArn = snsService.createTopic("market-alerts", null, null, REGION).getTopicArn();
+ snsService.subscribe(topicArn, "application", device.getArn(), REGION, Map.of());
+
+ snsService.publish(topicArn, null, null, "{\"default\":\"fallback body\"}", null, "json",
+ null, null, null, REGION);
+
+ List<PushNotification> captured = snsService.peekPushNotifications(device.getArn());
+ assertEquals(1, captured.size());
+ assertEquals("fallback body", captured.get(0).payload());
+ }
+
+ @Test
+ void publish_topicBroadcastRejectsJsonStructureMissingDefaultBeforeFanOut() {
+ PlatformApplication app = snsService.createPlatformApplication("android-app", "GCM", Map.of(), REGION);
+ PlatformEndpoint device = snsService.createPlatformEndpoint(app.getArn(), "fcm-token", null, Map.of(), REGION);
+
+ String topicArn = snsService.createTopic("market-alerts", null, null, REGION).getTopicArn();
+ snsService.subscribe(topicArn, "application", device.getArn(), REGION, Map.of());
+
+ AwsException e = assertThrows(AwsException.class, () -> snsService.publish(
+ topicArn, null, null, "{\"GCM\":\"only gcm\"}", null, "json",
+ null, null, null, REGION));
+ assertEquals("InvalidParameter", e.getErrorCode());
+ assertEquals(400, e.getHttpStatus());
+ assertTrue(e.getMessage().contains("default"));
+ assertTrue(snsService.peekPushNotifications(device.getArn()).isEmpty());
+ }
+
+ @Test
+ void publish_topicBroadcastRejectsInvalidJsonStructureBeforeFanOut() {
+ PlatformApplication app = snsService.createPlatformApplication("android-app", "GCM", Map.of(), REGION);
+ PlatformEndpoint device = snsService.createPlatformEndpoint(app.getArn(), "fcm-token", null, Map.of(), REGION);
+
+ String topicArn = snsService.createTopic("market-alerts", null, null, REGION).getTopicArn();
+ snsService.subscribe(topicArn, "application", device.getArn(), REGION, Map.of());
+
+ AwsException e = assertThrows(AwsException.class, () -> snsService.publish(
+ topicArn, null, null, "not json at all", null, "json",
+ null, null, null, REGION));
+ assertEquals("InvalidParameter", e.getErrorCode());
+ assertTrue(snsService.peekPushNotifications(device.getArn()).isEmpty());
+ }
+
+ @Test
+ void publishBatch_rejectsEntryWithJsonStructureMissingDefaultWithoutFailingBatch() {
+ PlatformApplication app = snsService.createPlatformApplication("android-app", "GCM", Map.of(), REGION);
+ PlatformEndpoint device = snsService.createPlatformEndpoint(app.getArn(), "fcm-token", null, Map.of(), REGION);
+
+ String topicArn = snsService.createTopic("market-alerts", null, null, REGION).getTopicArn();
+ snsService.subscribe(topicArn, "application", device.getArn(), REGION, Map.of());
+
+ var result = snsService.publishBatch(topicArn, List.of(
+ Map.of("Id", "bad", "Message", "{\"GCM\":\"only gcm\"}", "MessageStructure", "json"),
+ Map.of("Id", "good", "Message", "{\"default\":\"ok body\"}", "MessageStructure", "json")),
+ REGION);
+
+ assertEquals(1, result.failed().size());
+ assertEquals("bad", result.failed().get(0)[0]);
+ assertEquals("InvalidParameter", result.failed().get(0)[1]);
+ assertTrue(result.failed().get(0)[2].contains("default"));
+ assertEquals("true", result.failed().get(0)[3]);
+
+ assertEquals(1, result.successful().size());
+ assertEquals("good", result.successful().get(0)[0]);
+
+ List<PushNotification> captured = snsService.peekPushNotifications(device.getArn());
+ assertEquals(1, captured.size());
+ assertEquals("ok body", captured.get(0).payload());
+ }
+
+ @Test
+ void publishBatch_rejectsEntryWithInvalidJsonStructureWithoutFailingBatch() {
+ PlatformApplication app = snsService.createPlatformApplication("android-app", "GCM", Map.of(), REGION);
+ PlatformEndpoint device = snsService.createPlatformEndpoint(app.getArn(), "fcm-token", null, Map.of(), REGION);
+
+ String topicArn = snsService.createTopic("market-alerts", null, null, REGION).getTopicArn();
+ snsService.subscribe(topicArn, "application", device.getArn(), REGION, Map.of());
+
+ var result = snsService.publishBatch(topicArn, List.of(
+ Map.of("Id", "bad", "Message", "not json at all", "MessageStructure", "json"),
+ Map.of("Id", "good", "Message", "plain text")),
+ REGION);
+
+ assertEquals(1, result.failed().size());
+ assertEquals("bad", result.failed().get(0)[0]);
+ assertEquals("InvalidParameter", result.failed().get(0)[1]);
+ assertEquals(1, result.successful().size());
+ assertEquals("good", result.successful().get(0)[0]);
+
+ List<PushNotification> captured = snsService.peekPushNotifications(device.getArn());
+ assertEquals(1, captured.size());
+ assertEquals("plain text", captured.get(0).payload());
+ }
+
// --- Inspection helpers ---
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/sns/SnsProtocolPayloadResolutionTest.java b/src/test/java/io/github/hectorvent/floci/services/sns/SnsProtocolPayloadResolutionTest.java
new file mode 100644
index 0000000000..0e02636f3d
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/sns/SnsProtocolPayloadResolutionTest.java
@@ -0,0 +1,159 @@
+package io.github.hectorvent.floci.services.sns;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+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;
+import io.github.hectorvent.floci.services.sqs.SqsService;
+import io.github.hectorvent.floci.services.sqs.SqsServiceFactory;
+import io.github.hectorvent.floci.services.sqs.model.Message;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Tests that {@code MessageStructure="json"} resolves a per-protocol payload for every
+ * subscription protocol, not just {@code application}, matching real SNS: each subscriber
+ * receives the value under its protocol key, falling back to {@code default}.
+ */
+class SnsProtocolPayloadResolutionTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String ACCOUNT = "000000000000";
+ private static final String BASE_URL = "http://localhost:4566";
+
+ private SnsService snsService;
+ private SqsService sqsService;
+
+ @BeforeEach
+ void setUp() {
+ RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
+ sqsService = SqsServiceFactory.createInMemory(BASE_URL, regionResolver);
+ snsService = new SnsService(new InMemoryStorage<>(), new InMemoryStorage<>(),
+ regionResolver, sqsService, null);
+ }
+
+ @Test
+ void publish_jsonStructure_deliversSqsKeyToRawSqsSubscriber() {
+ String queueUrl = subscribeQueue("raw-queue", Map.of("RawMessageDelivery", "true"));
+
+ snsService.publish(topic("alerts"), null, null,
+ "{\"default\":\"hello\",\"sqs\":\"hi sqs\"}", null, "json",
+ null, null, null, REGION);
+
+ List<Message> messages = sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION);
+ assertEquals(1, messages.size());
+ assertEquals("hi sqs", messages.get(0).getBody());
+ }
+
+ @Test
+ void publish_jsonStructure_embedsSqsKeyInSnsEnvelope() {
+ String queueUrl = subscribeQueue("envelope-queue", Map.of());
+
+ snsService.publish(topic("alerts"), null, null,
+ "{\"default\":\"hello\",\"sqs\":\"hi sqs\"}", null, "json",
+ null, null, null, REGION);
+
+ List<Message> messages = sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION);
+ assertEquals(1, messages.size());
+ String body = messages.get(0).getBody();
+ assertTrue(body.contains("\"Message\":\"hi sqs\""),
+ "SNS envelope should carry the resolved sqs payload, got: " + body);
+ assertFalse(body.contains("\\\"default\\\""),
+ "SNS envelope should not carry the raw json structure, got: " + body);
+ }
+
+ @Test
+ void publish_jsonStructure_fallsBackToDefaultWhenProtocolKeyAbsent() {
+ String queueUrl = subscribeQueue("fallback-queue", Map.of("RawMessageDelivery", "true"));
+
+ snsService.publish(topic("alerts"), null, null,
+ "{\"default\":\"hello\",\"GCM\":\"push only\"}", null, "json",
+ null, null, null, REGION);
+
+ List<Message> messages = sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION);
+ assertEquals(1, messages.size());
+ assertEquals("hello", messages.get(0).getBody());
+ }
+
+ @Test
+ void publish_jsonStructure_ignoresNonStringProtocolKeyAndFallsBackToDefault() {
+ String queueUrl = subscribeQueue("nonstring-queue", Map.of("RawMessageDelivery", "true"));
+
+ // Real SNS ignores a key whose value isn't a string, delivering default instead of "42".
+ snsService.publish(topic("alerts"), null, null,
+ "{\"default\":\"hi\",\"sqs\":42}", null, "json",
+ null, null, null, REGION);
+
+ List<Message> messages = sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION);
+ assertEquals(1, messages.size());
+ assertEquals("hi", messages.get(0).getBody());
+ }
+
+ @Test
+ void publish_jsonStructure_rejectsNonStringDefault() {
+ subscribeQueue("nonstring-default-queue", Map.of("RawMessageDelivery", "true"));
+
+ AwsException ex = assertThrows(AwsException.class, () -> snsService.publish(
+ topic("alerts"), null, null,
+ "{\"default\":42}", null, "json",
+ null, null, null, REGION));
+ assertEquals("InvalidParameter", ex.getErrorCode());
+ }
+
+ @Test
+ void publish_withoutJsonStructure_deliversRawMessageUnchanged() {
+ String queueUrl = subscribeQueue("plain-queue", Map.of("RawMessageDelivery", "true"));
+
+ snsService.publish(topic("alerts"), null, null,
+ "{\"default\":\"hello\",\"sqs\":\"hi sqs\"}", null, null,
+ null, null, null, REGION);
+
+ List<Message> messages = sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION);
+ assertEquals(1, messages.size());
+ assertEquals("{\"default\":\"hello\",\"sqs\":\"hi sqs\"}", messages.get(0).getBody());
+ }
+
+ @Test
+ void publish_jsonStructure_resolvesPerProtocolForSqsAndPlatformEndpointOnSameTopic() {
+ String topicArn = topic("mixed");
+ String queueUrl = subscribeQueueTo(topicArn, "mixed-queue", Map.of("RawMessageDelivery", "true"));
+
+ PlatformApplication app = snsService.createPlatformApplication("android-app", "GCM", Map.of(), REGION);
+ PlatformEndpoint device = snsService.createPlatformEndpoint(app.getArn(), "fcm-token", null, Map.of(), REGION);
+ snsService.subscribe(topicArn, "application", device.getArn(), REGION, Map.of());
+
+ snsService.publish(topicArn, null, null,
+ "{\"default\":\"hello\",\"sqs\":\"hi sqs\",\"GCM\":\"hi device\"}", null, "json",
+ null, null, null, REGION);
+
+ List<Message> messages = sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION);
+ assertEquals(1, messages.size());
+ assertEquals("hi sqs", messages.get(0).getBody());
+
+ List<PushNotification> captured = snsService.peekPushNotifications(device.getArn());
+ assertEquals(1, captured.size());
+ assertEquals("hi device", captured.get(0).payload());
+ }
+
+ private String topic(String name) {
+ return snsService.createTopic(name, null, null, REGION).getTopicArn();
+ }
+
+ private String subscribeQueue(String queueName, Map<String, String> attributes) {
+ return subscribeQueueTo(topic("alerts"), queueName, attributes);
+ }
+
+ private String subscribeQueueTo(String topicArn, String queueName, Map<String, String> attributes) {
+ sqsService.createQueue(queueName, Map.of(), REGION);
+ String queueArn = "arn:aws:sqs:" + REGION + ":" + ACCOUNT + ":" + queueName;
+ snsService.subscribe(topicArn, "sqs", queueArn, REGION, attributes);
+ return BASE_URL + "/" + ACCOUNT + "/" + queueName;
+ }
+}