feat(sns): mock mobile push for iOS and Android platform endpoints (#1115)

This commit is contained in:
Clément authored and GitHub committed 2026-06-02 01:25:17 -05:00
1 parent 73a4b69ccf
commit 5dc0664b8b
9 files changed
+1228 -6

No files matched your search

@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.sns;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
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.Subscription;
import io.github.hectorvent.floci.services.sns.model.Topic;
import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;
@@ -54,6 +56,16 @@ public class SnsJsonHandler {
case "TagResource" -> handleTagResource(request, region);
case "UntagResource" -> handleUntagResource(request, region);
case "ListTagsForResource" -> handleListTagsForResource(request, region);
case "CreatePlatformApplication" -> handleCreatePlatformApplication(request, region);
case "DeletePlatformApplication" -> handleDeletePlatformApplication(request, region);
case "GetPlatformApplicationAttributes" -> handleGetPlatformApplicationAttributes(request, region);
case "SetPlatformApplicationAttributes" -> handleSetPlatformApplicationAttributes(request, region);
case "ListPlatformApplications" -> handleListPlatformApplications(region);
case "CreatePlatformEndpoint" -> handleCreatePlatformEndpoint(request, region);
case "DeleteEndpoint" -> handleDeleteEndpoint(request, region);
case "GetEndpointAttributes" -> handleGetEndpointAttributes(request, region);
case "SetEndpointAttributes" -> handleSetEndpointAttributes(request, region);
case "ListEndpointsByPlatformApplication" -> handleListEndpointsByPlatformApplication(request, region);
default -> Response.status(400)
.entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported."))
.build();
@@ -157,10 +169,12 @@ public class SnsJsonHandler {
String phoneNumber = request.path("PhoneNumber").asText(null);
String message = request.path("Message").asText(null);
String subject = request.path("Subject").asText(null);
String messageStructure = request.path("MessageStructure").asText(null);
Map<String, MessageAttributeValue> attributes = parseMessageAttributes(request.path("MessageAttributes"));
String messageId = snsService.publish(topicArn, targetArn, phoneNumber, message, subject, attributes, region);
String messageId = snsService.publish(topicArn, targetArn, phoneNumber, message, subject,
messageStructure, attributes, null, null, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("MessageId", messageId);
return Response.ok(response).build();
@@ -328,6 +342,108 @@ public class SnsJsonHandler {
return attributes;
}
private Response handleCreatePlatformApplication(JsonNode request, String region) {
String name = request.path("Name").asText(null);
String platform = request.path("Platform").asText(null);
Map<String, String> attributes = jsonNodeToMap(request.path("Attributes"));
PlatformApplication app = snsService.createPlatformApplication(name, platform, attributes, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("PlatformApplicationArn", app.getArn());
return Response.ok(response).build();
}
private Response handleDeletePlatformApplication(JsonNode request, String region) {
String arn = request.path("PlatformApplicationArn").asText(null);
snsService.deletePlatformApplication(arn, region);
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleGetPlatformApplicationAttributes(JsonNode request, String region) {
String arn = request.path("PlatformApplicationArn").asText(null);
Map<String, String> attrs = snsService.getPlatformApplicationAttributes(arn, region);
ObjectNode response = objectMapper.createObjectNode();
ObjectNode attrsNode = response.putObject("Attributes");
for (var entry : attrs.entrySet()) {
attrsNode.put(entry.getKey(), entry.getValue());
}
return Response.ok(response).build();
}
private Response handleSetPlatformApplicationAttributes(JsonNode request, String region) {
String arn = request.path("PlatformApplicationArn").asText(null);
Map<String, String> attrs = jsonNodeToMap(request.path("Attributes"));
snsService.setPlatformApplicationAttributes(arn, attrs, region);
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleListPlatformApplications(String region) {
List<PlatformApplication> apps = snsService.listPlatformApplications(region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode arr = response.putArray("PlatformApplications");
for (PlatformApplication app : apps) {
ObjectNode node = objectMapper.createObjectNode();
node.put("PlatformApplicationArn", app.getArn());
ObjectNode attrsNode = node.putObject("Attributes");
for (var entry : app.getAttributes().entrySet()) {
attrsNode.put(entry.getKey(), entry.getValue());
}
arr.add(node);
}
return Response.ok(response).build();
}
private Response handleCreatePlatformEndpoint(JsonNode request, String region) {
String appArn = request.path("PlatformApplicationArn").asText(null);
String token = request.path("Token").asText(null);
String customUserData = request.path("CustomUserData").asText(null);
Map<String, String> attributes = jsonNodeToMap(request.path("Attributes"));
PlatformEndpoint endpoint = snsService.createPlatformEndpoint(appArn, token, customUserData, attributes, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("EndpointArn", endpoint.getArn());
return Response.ok(response).build();
}
private Response handleDeleteEndpoint(JsonNode request, String region) {
String arn = request.path("EndpointArn").asText(null);
snsService.deleteEndpoint(arn, region);
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleGetEndpointAttributes(JsonNode request, String region) {
String arn = request.path("EndpointArn").asText(null);
Map<String, String> attrs = snsService.getEndpointAttributes(arn, region);
ObjectNode response = objectMapper.createObjectNode();
ObjectNode attrsNode = response.putObject("Attributes");
for (var entry : attrs.entrySet()) {
attrsNode.put(entry.getKey(), entry.getValue());
}
return Response.ok(response).build();
}
private Response handleSetEndpointAttributes(JsonNode request, String region) {
String arn = request.path("EndpointArn").asText(null);
Map<String, String> attrs = jsonNodeToMap(request.path("Attributes"));
snsService.setEndpointAttributes(arn, attrs, region);
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleListEndpointsByPlatformApplication(JsonNode request, String region) {
String appArn = request.path("PlatformApplicationArn").asText(null);
List<PlatformEndpoint> endpoints = snsService.listEndpointsByPlatformApplication(appArn, region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode arr = response.putArray("Endpoints");
for (PlatformEndpoint ep : endpoints) {
ObjectNode node = objectMapper.createObjectNode();
node.put("EndpointArn", ep.getArn());
ObjectNode attrsNode = node.putObject("Attributes");
for (var entry : ep.getAttributes().entrySet()) {
attrsNode.put(entry.getKey(), entry.getValue());
}
arr.add(node);
}
return Response.ok(response).build();
}
private Map<String, String> jsonNodeToMap(JsonNode node) {
Map<String, String> map = new HashMap<>();
if (node != null && node.isObject()) {
@@ -0,0 +1,81 @@
package io.github.hectorvent.floci.services.sns;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.services.sns.model.PushNotification;
import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;
import jakarta.inject.Inject;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.List;
import java.util.Map;
/**
* Floci-specific inspection endpoint for captured mobile push notifications.
* SNS push delivery is mocked — APNS and FCM are never contacted, so tests need
* a way to assert what would have been sent. This controller exposes that capture.
*/
@Path("/_aws/sns/push-notifications")
@Produces(MediaType.APPLICATION_JSON)
public class SnsPushInspectionController {
private final SnsService snsService;
private final ObjectMapper objectMapper;
@Inject
public SnsPushInspectionController(SnsService snsService, ObjectMapper objectMapper) {
this.snsService = snsService;
this.objectMapper = objectMapper;
}
@GET
public Response getPushNotifications(@QueryParam("EndpointArn") String endpointArn) {
List<PushNotification> captured = snsService.peekPushNotifications(endpointArn);
ArrayNode arr = objectMapper.createArrayNode();
for (PushNotification p : captured) {
ObjectNode node = objectMapper.createObjectNode();
node.put("MessageId", p.messageId());
node.put("EndpointArn", p.endpointArn());
node.put("PlatformApplicationArn", p.platformApplicationArn());
node.put("Platform", p.platform());
node.put("Token", p.token());
node.put("Payload", p.payload());
if (p.subject() != null) {
node.put("Subject", p.subject());
} else {
node.putNull("Subject");
}
node.put("Timestamp", p.timestamp().toString());
ObjectNode attrs = node.putObject("MessageAttributes");
if (p.messageAttributes() != null) {
for (Map.Entry<String, MessageAttributeValue> entry : p.messageAttributes().entrySet()) {
ObjectNode attr = attrs.putObject(entry.getKey());
attr.put("DataType", entry.getValue().getDataType());
if (entry.getValue().getStringValue() != null) {
attr.put("StringValue", entry.getValue().getStringValue());
}
if (entry.getValue().getBinaryValue() != null) {
attr.put("BinaryValue", entry.getValue().getBinaryValue());
}
}
}
arr.add(node);
}
ObjectNode result = objectMapper.createObjectNode();
result.set("notifications", arr);
return Response.ok(result).build();
}
@DELETE
public Response clearPushNotifications() {
snsService.clearPushNotifications();
return Response.ok().build();
}
}
@@ -1,6 +1,8 @@
package io.github.hectorvent.floci.services.sns;
import io.github.hectorvent.floci.core.common.*;
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.Subscription;
import io.github.hectorvent.floci.services.sns.model.Topic;
import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;
@@ -53,6 +55,16 @@ public class SnsQueryHandler {
case "TagResource" -> handleTagResource(params, region);
case "UntagResource" -> handleUntagResource(params, region);
case "ListTagsForResource" -> handleListTagsForResource(params, region);
case "CreatePlatformApplication" -> handleCreatePlatformApplication(params, region);
case "DeletePlatformApplication" -> handleDeletePlatformApplication(params, region);
case "GetPlatformApplicationAttributes" -> handleGetPlatformApplicationAttributes(params, region);
case "SetPlatformApplicationAttributes" -> handleSetPlatformApplicationAttributes(params, region);
case "ListPlatformApplications" -> handleListPlatformApplications(region);
case "CreatePlatformEndpoint" -> handleCreatePlatformEndpoint(params, region);
case "DeleteEndpoint" -> handleDeleteEndpoint(params, region);
case "GetEndpointAttributes" -> handleGetEndpointAttributes(params, region);
case "SetEndpointAttributes" -> handleSetEndpointAttributes(params, region);
case "ListEndpointsByPlatformApplication" -> handleListEndpointsByPlatformApplication(params, region);
default -> AwsQueryResponse.error("UnsupportedOperation",
"Operation " + action + " is not supported by SNS.", AwsNamespaces.SNS, 400);
};
@@ -181,6 +193,7 @@ public class SnsQueryHandler {
String phoneNumber = getParam(params, "PhoneNumber");
String message = getParam(params, "Message");
String subject = getParam(params, "Subject");
String messageStructure = getParam(params, "MessageStructure");
String messageGroupId = getParam(params, "MessageGroupId");
String messageDeduplicationId = getParam(params, "MessageDeduplicationId");
@@ -193,7 +206,7 @@ public class SnsQueryHandler {
try {
String messageId = snsService.publish(topicArn, targetArn, phoneNumber, message, subject,
attributes, messageGroupId, messageDeduplicationId, region);
messageStructure, attributes, messageGroupId, messageDeduplicationId, region);
String result = new XmlBuilder().elem("MessageId", messageId).build();
return Response.ok(AwsQueryResponse.envelope("Publish", AwsNamespaces.SNS, result)).build();
@@ -202,6 +215,130 @@ public class SnsQueryHandler {
}
}
private Response handleCreatePlatformApplication(MultivaluedMap<String, String> params, String region) {
String name = getParam(params, "Name");
String platform = getParam(params, "Platform");
Map<String, String> attributes = extractSnsAttributes(params, "Attributes");
try {
PlatformApplication app = snsService.createPlatformApplication(name, platform, attributes, region);
String result = new XmlBuilder().elem("PlatformApplicationArn", app.getArn()).build();
return Response.ok(AwsQueryResponse.envelope("CreatePlatformApplication", AwsNamespaces.SNS, result)).build();
} catch (AwsException e) {
return xmlErrorResponse(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
}
}
private Response handleDeletePlatformApplication(MultivaluedMap<String, String> params, String region) {
String arn = getParam(params, "PlatformApplicationArn");
snsService.deletePlatformApplication(arn, region);
return Response.ok(AwsQueryResponse.envelopeNoResult("DeletePlatformApplication", AwsNamespaces.SNS)).build();
}
private Response handleGetPlatformApplicationAttributes(MultivaluedMap<String, String> params, String region) {
String arn = getParam(params, "PlatformApplicationArn");
try {
Map<String, String> attrs = snsService.getPlatformApplicationAttributes(arn, region);
var xml = new XmlBuilder().start("Attributes");
for (var entry : attrs.entrySet()) {
xml.start("entry").elem("key", entry.getKey()).elem("value", entry.getValue()).end("entry");
}
xml.end("Attributes");
return Response.ok(AwsQueryResponse.envelope("GetPlatformApplicationAttributes", AwsNamespaces.SNS, xml.build())).build();
} catch (AwsException e) {
return xmlErrorResponse(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
}
}
private Response handleSetPlatformApplicationAttributes(MultivaluedMap<String, String> params, String region) {
String arn = getParam(params, "PlatformApplicationArn");
Map<String, String> attrs = extractSnsAttributes(params, "Attributes");
try {
snsService.setPlatformApplicationAttributes(arn, attrs, region);
return Response.ok(AwsQueryResponse.envelopeNoResult("SetPlatformApplicationAttributes", AwsNamespaces.SNS)).build();
} catch (AwsException e) {
return xmlErrorResponse(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
}
}
private Response handleListPlatformApplications(String region) {
List<PlatformApplication> apps = snsService.listPlatformApplications(region);
var xml = new XmlBuilder().start("PlatformApplications");
for (PlatformApplication app : apps) {
xml.start("member").elem("PlatformApplicationArn", app.getArn()).start("Attributes");
for (var entry : app.getAttributes().entrySet()) {
xml.start("entry").elem("key", entry.getKey()).elem("value", entry.getValue()).end("entry");
}
xml.end("Attributes").end("member");
}
xml.end("PlatformApplications");
return Response.ok(AwsQueryResponse.envelope("ListPlatformApplications", AwsNamespaces.SNS, xml.build())).build();
}
private Response handleCreatePlatformEndpoint(MultivaluedMap<String, String> params, String region) {
String appArn = getParam(params, "PlatformApplicationArn");
String token = getParam(params, "Token");
String customUserData = getParam(params, "CustomUserData");
Map<String, String> attrs = extractSnsAttributes(params, "Attributes");
try {
PlatformEndpoint endpoint = snsService.createPlatformEndpoint(appArn, token, customUserData, attrs, region);
String result = new XmlBuilder().elem("EndpointArn", endpoint.getArn()).build();
return Response.ok(AwsQueryResponse.envelope("CreatePlatformEndpoint", AwsNamespaces.SNS, result)).build();
} catch (AwsException e) {
return xmlErrorResponse(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
}
}
private Response handleDeleteEndpoint(MultivaluedMap<String, String> params, String region) {
String arn = getParam(params, "EndpointArn");
snsService.deleteEndpoint(arn, region);
return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteEndpoint", AwsNamespaces.SNS)).build();
}
private Response handleGetEndpointAttributes(MultivaluedMap<String, String> params, String region) {
String arn = getParam(params, "EndpointArn");
try {
Map<String, String> attrs = snsService.getEndpointAttributes(arn, region);
var xml = new XmlBuilder().start("Attributes");
for (var entry : attrs.entrySet()) {
xml.start("entry").elem("key", entry.getKey()).elem("value", entry.getValue()).end("entry");
}
xml.end("Attributes");
return Response.ok(AwsQueryResponse.envelope("GetEndpointAttributes", AwsNamespaces.SNS, xml.build())).build();
} catch (AwsException e) {
return xmlErrorResponse(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
}
}
private Response handleSetEndpointAttributes(MultivaluedMap<String, String> params, String region) {
String arn = getParam(params, "EndpointArn");
Map<String, String> attrs = extractSnsAttributes(params, "Attributes");
try {
snsService.setEndpointAttributes(arn, attrs, region);
return Response.ok(AwsQueryResponse.envelopeNoResult("SetEndpointAttributes", AwsNamespaces.SNS)).build();
} catch (AwsException e) {
return xmlErrorResponse(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
}
}
private Response handleListEndpointsByPlatformApplication(MultivaluedMap<String, String> params, String region) {
String appArn = getParam(params, "PlatformApplicationArn");
try {
List<PlatformEndpoint> endpoints = snsService.listEndpointsByPlatformApplication(appArn, region);
var xml = new XmlBuilder().start("Endpoints");
for (PlatformEndpoint ep : endpoints) {
xml.start("member").elem("EndpointArn", ep.getArn()).start("Attributes");
for (var entry : ep.getAttributes().entrySet()) {
xml.start("entry").elem("key", entry.getKey()).elem("value", entry.getValue()).end("entry");
}
xml.end("Attributes").end("member");
}
xml.end("Endpoints");
return Response.ok(AwsQueryResponse.envelope("ListEndpointsByPlatformApplication", AwsNamespaces.SNS, xml.build())).build();
} catch (AwsException e) {
return xmlErrorResponse(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
}
}
private Response handlePublishBatch(MultivaluedMap<String, String> params, String region) {
String topicArn = getParam(params, "TopicArn");
List<Map<String, Object>> entries = new ArrayList<>();
@@ -8,6 +8,9 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
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.sns.model.Subscription;
import io.github.hectorvent.floci.services.sns.model.Topic;
import io.github.hectorvent.floci.services.sqs.SqsService;
@@ -34,12 +37,15 @@ import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.Deque;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
@ApplicationScoped
public class SnsService {
@@ -47,11 +53,18 @@ public class SnsService {
private static final Logger LOG = Logger.getLogger(SnsService.class);
private static final Duration FIFO_DEDUP_WINDOW = Duration.ofMinutes(5);
private static final int MAX_PUBLISH_SIZE = 262_144;
private static final int PUSH_CAPTURE_LIMIT = 1000;
private static final List<String> PENDING_CONFIRMATION_PROTOCOLS =
List.of("http", "https", "email", "email-json", "sms");
/** Mobile-push platforms Floci mocks. iOS and Android only — anything else is rejected. */
private static final Set<String> SUPPORTED_PUSH_PLATFORMS = Set.of(
"APNS", "APNS_SANDBOX", "GCM", "FCM");
private final StorageBackend<String, Topic> topicStore;
private final StorageBackend<String, Subscription> subscriptionStore;
private final StorageBackend<String, PlatformApplication> platformAppStore;
private final StorageBackend<String, PlatformEndpoint> platformEndpointStore;
private final Deque<PushNotification> pushCapture = new ConcurrentLinkedDeque<>();
private final RegionResolver regionResolver;
private final SqsService sqsService;
private final LambdaService lambdaService;
@@ -72,6 +85,12 @@ public class SnsService {
storageFactory.create("sns", "sns-subscriptions.json",
new TypeReference<Map<String, Subscription>>() {
}),
storageFactory.create("sns", "sns-platform-applications.json",
new TypeReference<Map<String, PlatformApplication>>() {
}),
storageFactory.create("sns", "sns-platform-endpoints.json",
new TypeReference<Map<String, PlatformEndpoint>>() {
}),
regionResolver,
sqsService,
lambdaService,
@@ -87,8 +106,22 @@ public class SnsService {
StorageBackend<String, Subscription> subscriptionStore,
RegionResolver regionResolver, SqsService sqsService,
LambdaService lambdaService) {
this(topicStore, subscriptionStore,
new io.github.hectorvent.floci.core.storage.InMemoryStorage<>(),
new io.github.hectorvent.floci.core.storage.InMemoryStorage<>(),
regionResolver, sqsService, lambdaService);
}
SnsService(StorageBackend<String, Topic> topicStore,
StorageBackend<String, Subscription> subscriptionStore,
StorageBackend<String, PlatformApplication> platformAppStore,
StorageBackend<String, PlatformEndpoint> platformEndpointStore,
RegionResolver regionResolver, SqsService sqsService,
LambdaService lambdaService) {
this.topicStore = topicStore;
this.subscriptionStore = subscriptionStore;
this.platformAppStore = platformAppStore;
this.platformEndpointStore = platformEndpointStore;
this.regionResolver = regionResolver;
this.sqsService = sqsService;
this.lambdaService = lambdaService;
@@ -99,10 +132,14 @@ public class SnsService {
SnsService(StorageBackend<String, Topic> topicStore,
StorageBackend<String, Subscription> subscriptionStore,
StorageBackend<String, PlatformApplication> platformAppStore,
StorageBackend<String, PlatformEndpoint> platformEndpointStore,
RegionResolver regionResolver, SqsService sqsService,
LambdaService lambdaService, String baseUrl, ObjectMapper objectMapper) {
this.topicStore = topicStore;
this.subscriptionStore = subscriptionStore;
this.platformAppStore = platformAppStore;
this.platformEndpointStore = platformEndpointStore;
this.regionResolver = regionResolver;
this.sqsService = sqsService;
this.lambdaService = lambdaService;
@@ -301,6 +338,14 @@ public class SnsService {
public String publish(String topicArn, String targetArn, String phoneNumber, String message,
String subject, Map<String, MessageAttributeValue> messageAttributes,
String messageGroupId, String messageDeduplicationId, String region) {
return publish(topicArn, targetArn, phoneNumber, message, subject, null,
messageAttributes, messageGroupId, messageDeduplicationId, region);
}
public String publish(String topicArn, String targetArn, String phoneNumber, String message,
String subject, String messageStructure,
Map<String, MessageAttributeValue> messageAttributes,
String messageGroupId, String messageDeduplicationId, String region) {
int messageBytes = message == null ? 0 : message.getBytes(StandardCharsets.UTF_8).length;
int payloadSize = computePublishSize(messageBytes, subject, messageAttributes);
if (payloadSize > MAX_PUBLISH_SIZE) {
@@ -318,13 +363,24 @@ public class SnsService {
if (effectiveArn == null) {
throw new AwsException("InvalidParameter", "TopicArn or TargetArn is required.", 400);
}
String topicStoreKey = topicKey(region, effectiveArn);
Topic topic = topicStore.get(topicStoreKey)
.orElseThrow(() -> new AwsException("NotFound", "Topic does not exist.", 404));
if (message == null || message.isBlank()) {
throw new AwsException("InvalidParameter", "Message is required.", 400);
}
if (isEndpointArn(effectiveArn)) {
return publishToEndpoint(effectiveArn, message, subject, messageStructure,
messageAttributes, region);
}
if (isPlatformApplicationArn(effectiveArn)) {
throw new AwsException("InvalidParameter",
"Invalid parameter: TargetArn Reason: Cannot publish directly to a platform application ARN.",
400);
}
String topicStoreKey = topicKey(region, effectiveArn);
Topic topic = topicStore.get(topicStoreKey)
.orElseThrow(() -> new AwsException("NotFound", "Topic does not exist.", 404));
boolean isFifo = "true".equals(topic.getAttributes().get("FifoTopic"));
String dedupId = messageDeduplicationId;
if (isFifo) {
@@ -362,6 +418,269 @@ public class SnsService {
return messageId;
}
// --- Mobile push (iOS / Android) ---
public PlatformApplication createPlatformApplication(String name, String platform,
Map<String, String> attributes, String region) {
if (name == null || name.isBlank()) {
throw new AwsException("InvalidParameter", "Name is required.", 400);
}
if (platform == null || !SUPPORTED_PUSH_PLATFORMS.contains(platform)) {
throw new AwsException("InvalidParameter",
"Invalid parameter: Platform Reason: Floci mocks only APNS, APNS_SANDBOX, GCM, and FCM.",
400);
}
String arn = platformApplicationArn(region, platform, name);
String key = platformAppKey(region, arn);
PlatformApplication existing = platformAppStore.get(key).orElse(null);
if (existing != null) return existing;
PlatformApplication app = new PlatformApplication(name, arn, platform);
if (attributes != null) app.getAttributes().putAll(attributes);
platformAppStore.put(key, app);
LOG.infov("Created SNS platform application: {0} ({1}) in {2}", name, platform, region);
return app;
}
public void deletePlatformApplication(String arn, String region) {
String key = platformAppKey(region, arn);
if (platformAppStore.get(key).isEmpty()) {
return; // AWS treats DeletePlatformApplication as idempotent
}
String endpointPrefix = "endpoint::" + region + "::";
List<String> toDelete = new ArrayList<>();
for (String endpointKey : platformEndpointStore.keys()) {
if (!endpointKey.startsWith(endpointPrefix)) continue;
platformEndpointStore.get(endpointKey).ifPresent(ep -> {
if (arn.equals(ep.getPlatformApplicationArn())) toDelete.add(endpointKey);
});
}
toDelete.forEach(platformEndpointStore::delete);
platformAppStore.delete(key);
LOG.infov("Deleted SNS platform application: {0}", arn);
}
public Map<String, String> getPlatformApplicationAttributes(String arn, String region) {
String key = platformAppKey(region, arn);
PlatformApplication app = platformAppStore.get(key)
.orElseThrow(() -> new AwsException("NotFound",
"PlatformApplication does not exist.", 404));
return new java.util.LinkedHashMap<>(app.getAttributes());
}
public void setPlatformApplicationAttributes(String arn, Map<String, String> attributes, String region) {
String key = platformAppKey(region, arn);
PlatformApplication app = platformAppStore.get(key)
.orElseThrow(() -> new AwsException("NotFound",
"PlatformApplication does not exist.", 404));
if (attributes != null) app.getAttributes().putAll(attributes);
platformAppStore.put(key, app);
}
public List<PlatformApplication> listPlatformApplications(String region) {
String prefix = "app::" + region + "::";
return platformAppStore.scan(k -> k.startsWith(prefix));
}
public PlatformEndpoint createPlatformEndpoint(String platformApplicationArn, String token,
String customUserData, Map<String, String> attributes,
String region) {
if (token == null || token.isBlank()) {
throw new AwsException("InvalidParameter", "Token is required.", 400);
}
String appKey = platformAppKey(region, platformApplicationArn);
PlatformApplication app = platformAppStore.get(appKey)
.orElseThrow(() -> new AwsException("NotFound",
"PlatformApplication does not exist.", 404));
if ("false".equalsIgnoreCase(app.getAttributes().get("Enabled"))) {
throw new AwsException("PlatformApplicationDisabledException",
"Platform application is disabled.", 400);
}
String endpointPrefix = "endpoint::" + region + "::";
for (String key : platformEndpointStore.keys()) {
if (!key.startsWith(endpointPrefix)) continue;
PlatformEndpoint existing = platformEndpointStore.get(key).orElse(null);
if (existing == null) continue;
if (!platformApplicationArn.equals(existing.getPlatformApplicationArn())) continue;
if (!token.equals(existing.getToken())) continue;
// AWS idempotency: same token + same attributes -> return existing; otherwise reject.
String existingUserData = existing.getAttributes().getOrDefault("CustomUserData", "");
String newUserData = customUserData != null ? customUserData : "";
boolean sameAttrs = existingUserData.equals(newUserData)
&& (attributes == null || matchesExistingAttributes(existing, attributes));
if (sameAttrs) return existing;
throw new AwsException("InvalidParameter",
"Invalid parameter: Token Reason: Endpoint " + existing.getArn()
+ " already exists with the same Token, but different attributes.",
400);
}
String endpointArn = platformEndpointArn(region, app.getPlatform(), app.getName());
PlatformEndpoint endpoint = new PlatformEndpoint(endpointArn, platformApplicationArn, token);
if (customUserData != null) endpoint.getAttributes().put("CustomUserData", customUserData);
if (attributes != null) endpoint.getAttributes().putAll(attributes);
if (isExpiredSentinelToken(token)) {
// Fast-path for tests: the token is "already expired" — AWS would normally only
// mark Enabled=false after an async APNS/FCM failure; Floci does it on create.
endpoint.getAttributes().put("Enabled", "false");
LOG.infov("Endpoint {0} created with Enabled=false (token matches expired sentinel)", endpointArn);
}
platformEndpointStore.put(endpointKey(region, endpointArn), endpoint);
LOG.infov("Created SNS platform endpoint: {0} for application {1}", endpointArn, platformApplicationArn);
return endpoint;
}
public void deleteEndpoint(String endpointArn, String region) {
// AWS treats DeleteEndpoint as idempotent — no error if missing.
platformEndpointStore.delete(endpointKey(region, endpointArn));
LOG.infov("Deleted SNS platform endpoint: {0}", endpointArn);
}
public Map<String, String> getEndpointAttributes(String endpointArn, String region) {
PlatformEndpoint endpoint = platformEndpointStore.get(endpointKey(region, endpointArn))
.orElseThrow(() -> new AwsException("NotFound", "Endpoint does not exist.", 404));
return new java.util.LinkedHashMap<>(endpoint.getAttributes());
}
public void setEndpointAttributes(String endpointArn, Map<String, String> attributes, String region) {
String key = endpointKey(region, endpointArn);
PlatformEndpoint endpoint = platformEndpointStore.get(key)
.orElseThrow(() -> new AwsException("NotFound", "Endpoint does not exist.", 404));
if (attributes != null) endpoint.getAttributes().putAll(attributes);
platformEndpointStore.put(key, endpoint);
}
public List<PlatformEndpoint> listEndpointsByPlatformApplication(String platformApplicationArn, String region) {
String prefix = "endpoint::" + region + "::";
List<PlatformEndpoint> result = new ArrayList<>();
for (String key : platformEndpointStore.keys()) {
if (!key.startsWith(prefix)) continue;
platformEndpointStore.get(key).ifPresent(ep -> {
if (platformApplicationArn.equals(ep.getPlatformApplicationArn())) result.add(ep);
});
}
return result;
}
/** Returns the most recent captured pushes (newest first), optionally filtered by endpoint ARN. */
public List<PushNotification> peekPushNotifications(String endpointArn) {
List<PushNotification> out = new ArrayList<>();
for (PushNotification p : pushCapture) {
if (endpointArn != null && !endpointArn.equals(p.endpointArn())) continue;
out.add(p);
}
return out;
}
public void clearPushNotifications() {
pushCapture.clear();
}
private String publishToEndpoint(String endpointArn, String message, String subject,
String messageStructure,
Map<String, MessageAttributeValue> messageAttributes,
String region) {
PlatformEndpoint endpoint = platformEndpointStore.get(endpointKey(region, endpointArn))
.orElseThrow(() -> new AwsException("NotFound", "Endpoint does not exist.", 404));
if (!"true".equalsIgnoreCase(endpoint.getAttributes().getOrDefault("Enabled", "true"))) {
throw new AwsException("EndpointDisabledException",
"Endpoint " + endpointArn + " disabled", 400);
}
PlatformApplication app = platformAppStore.get(platformAppKey(region, endpoint.getPlatformApplicationArn()))
.orElseThrow(() -> new AwsException("NotFound",
"PlatformApplication does not exist.", 404));
if ("false".equalsIgnoreCase(app.getAttributes().get("Enabled"))) {
throw new AwsException("PlatformApplicationDisabledException",
"Platform application is disabled.", 400);
}
String payload = resolvePushPayload(app.getPlatform(), message, messageStructure);
String messageId = UUID.randomUUID().toString();
recordPushNotification(new PushNotification(
endpoint.getArn(), app.getArn(), app.getPlatform(), endpoint.getToken(),
payload, subject, messageAttributes, messageId, Instant.now()));
LOG.infov("Captured push notification {0} -> {1} ({2})", messageId, endpoint.getArn(), app.getPlatform());
return messageId;
}
/**
* 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.
*/
private String resolvePushPayload(String platform, String message, String messageStructure) {
if (messageStructure == null || !"json".equals(messageStructure)) {
return message;
}
JsonNode root;
try {
root = objectMapper.readTree(message);
} catch (Exception e) {
throw new AwsException("InvalidParameter",
"Invalid parameter: Message Reason: Message is not valid JSON.", 400);
}
if (!root.isObject() || !root.has("default")) {
throw new AwsException("InvalidParameter",
"Invalid parameter: Message Reason: Messages must be a JSON object with a 'default' key.",
400);
}
JsonNode platformValue = root.get(platform);
if (platformValue != null && !platformValue.isNull()) {
return platformValue.isTextual() ? platformValue.asText() : platformValue.toString();
}
return root.get("default").asText();
}
private void recordPushNotification(PushNotification notification) {
pushCapture.addFirst(notification);
while (pushCapture.size() > PUSH_CAPTURE_LIMIT) {
pushCapture.pollLast();
}
}
private boolean matchesExistingAttributes(PlatformEndpoint existing, Map<String, String> requested) {
for (Map.Entry<String, String> entry : requested.entrySet()) {
String existingValue = existing.getAttributes().get(entry.getKey());
if (existingValue == null) {
if (entry.getValue() != null && !entry.getValue().isEmpty()) return false;
} else if (!existingValue.equals(entry.getValue())) {
return false;
}
}
return true;
}
private static boolean isExpiredSentinelToken(String token) {
return token != null && token.toUpperCase(java.util.Locale.ROOT).contains("EXPIRED");
}
private static boolean isEndpointArn(String arn) {
return arn != null && arn.contains(":endpoint/");
}
private static boolean isPlatformApplicationArn(String arn) {
return arn != null && arn.contains(":app/");
}
private String platformApplicationArn(String region, String platform, String name) {
return regionResolver.buildArn("sns", region, "app/" + platform + "/" + name);
}
private String platformEndpointArn(String region, String platform, String appName) {
return regionResolver.buildArn("sns", region,
"endpoint/" + platform + "/" + appName + "/" + UUID.randomUUID());
}
private static String platformAppKey(String region, String arn) {
return "app::" + region + "::" + arn;
}
private static String endpointKey(String region, String arn) {
return "endpoint::" + region + "::" + arn;
}
public Map<String, String> getSubscriptionAttributes(String subscriptionArn, String region) {
String key = subKey(region, subscriptionArn);
Subscription sub = subscriptionStore.get(key)
@@ -0,0 +1,55 @@
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;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class PlatformApplication {
@JsonProperty("Name")
private String name;
@JsonProperty("PlatformApplicationArn")
private String arn;
/** APNS, APNS_SANDBOX, GCM, FCM. */
@JsonProperty("Platform")
private String platform;
@JsonProperty("Attributes")
private Map<String, String> attributes = new HashMap<>();
@JsonProperty("CreatedAt")
private Instant createdAt;
public PlatformApplication() {}
public PlatformApplication(String name, String arn, String platform) {
this.name = name;
this.arn = arn;
this.platform = platform;
this.createdAt = Instant.now();
this.attributes.put("Enabled", "true");
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public String getPlatform() { return platform; }
public void setPlatform(String platform) { this.platform = platform; }
public Map<String, String> getAttributes() { return attributes; }
public void setAttributes(Map<String, String> attributes) { this.attributes = attributes; }
public Instant getCreatedAt() { return createdAt; }
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
}
@@ -0,0 +1,56 @@
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;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class PlatformEndpoint {
@JsonProperty("EndpointArn")
private String arn;
@JsonProperty("PlatformApplicationArn")
private String platformApplicationArn;
@JsonProperty("Token")
private String token;
@JsonProperty("Attributes")
private Map<String, String> attributes = new HashMap<>();
@JsonProperty("CreatedAt")
private Instant createdAt;
public PlatformEndpoint() {}
public PlatformEndpoint(String arn, String platformApplicationArn, String token) {
this.arn = arn;
this.platformApplicationArn = platformApplicationArn;
this.token = token;
this.createdAt = Instant.now();
this.attributes.put("Token", token);
this.attributes.putIfAbsent("Enabled", "true");
this.attributes.putIfAbsent("CustomUserData", "");
}
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public String getPlatformApplicationArn() { return platformApplicationArn; }
public void setPlatformApplicationArn(String platformApplicationArn) { this.platformApplicationArn = platformApplicationArn; }
public String getToken() { return token; }
public void setToken(String token) { this.token = token; }
public Map<String, String> getAttributes() { return attributes; }
public void setAttributes(Map<String, String> attributes) { this.attributes = attributes; }
public Instant getCreatedAt() { return createdAt; }
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
}
@@ -0,0 +1,25 @@
package io.github.hectorvent.floci.services.sns.model;
import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.Map;
/**
* In-memory capture record for a push notification delivered to a platform endpoint.
* Not persisted — Floci is a mock; the deque holds the last N notifications so tests
* can assert what would have been sent to APNS or FCM.
*/
@RegisterForReflection
public record PushNotification(
String endpointArn,
String platformApplicationArn,
String platform,
String token,
String payload,
String subject,
Map<String, MessageAttributeValue> messageAttributes,
String messageId,
Instant timestamp
) {}