From 5dc0664b8b425b3ca7aa73a1192c3c02a4c1592d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment?= <57944998+ClementAndreDupuy@users.noreply.github.com> Date: Tue, 2 Jun 2026 07:25:17 +0100 Subject: [PATCH] feat(sns): mock mobile push for iOS and Android platform endpoints (#1115) --- docs/services/sns.md | 91 ++++- .../floci/services/sns/SnsJsonHandler.java | 118 +++++- .../sns/SnsPushInspectionController.java | 81 +++++ .../floci/services/sns/SnsQueryHandler.java | 139 ++++++- .../floci/services/sns/SnsService.java | 325 ++++++++++++++++- .../sns/model/PlatformApplication.java | 55 +++ .../services/sns/model/PlatformEndpoint.java | 56 +++ .../services/sns/model/PushNotification.java | 25 ++ .../floci/services/sns/SnsMobilePushTest.java | 344 ++++++++++++++++++ 9 files changed, 1228 insertions(+), 6 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/sns/SnsPushInspectionController.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/sns/model/PlatformApplication.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/sns/model/PlatformEndpoint.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/sns/model/PushNotification.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/sns/SnsMobilePushTest.java diff --git a/docs/services/sns.md b/docs/services/sns.md index 3f94bee76b..4f0f0a560e 100644 --- a/docs/services/sns.md +++ b/docs/services/sns.md @@ -24,6 +24,16 @@ | `TagResource` | Tag a topic | | `UntagResource` | Remove tags from a topic | | `ListTagsForResource` | List tags on a topic | +| `CreatePlatformApplication` | Create a mobile push platform app (iOS or Android) | +| `DeletePlatformApplication` | Delete a platform app and its endpoints | +| `GetPlatformApplicationAttributes` | Read platform app attributes | +| `SetPlatformApplicationAttributes` | Update platform app attributes (e.g. `Enabled`) | +| `ListPlatformApplications` | List platform applications in the region | +| `CreatePlatformEndpoint` | Register a device token under a platform app | +| `DeleteEndpoint` | Delete a platform endpoint | +| `GetEndpointAttributes` | Read endpoint attributes | +| `SetEndpointAttributes` | Update endpoint attributes (e.g. `Enabled=false` to simulate token expiry) | +| `ListEndpointsByPlatformApplication` | List endpoints under a platform app | ## Configuration @@ -75,4 +85,83 @@ Floci supports real SNS → SQS fan-out. When you publish to a topic, all SQS-su Supported subscription protocols: - `sqs` — delivers to a Floci SQS queue - `lambda` — invokes a Floci Lambda function -- `http` / `https` — posts to an HTTP endpoint \ No newline at end of file +- `http` / `https` — posts to an HTTP endpoint + +## Mobile push (mock) + +Floci mocks SNS mobile push for iOS and Android. No real APNS or FCM connection is +made — every push is captured in memory so tests can assert what would have been sent. + +**Supported platforms:** `APNS`, `APNS_SANDBOX`, `GCM`, `FCM`. Any other platform +value returns `InvalidParameter`. + +### End-to-end flow + +```bash +APP_ARN=$(aws sns create-platform-application \ + --name ios-app --platform APNS \ + --attributes PlatformCredential=fake-cert \ + --endpoint-url http://localhost:4566 --query PlatformApplicationArn --output text) + +ENDPOINT_ARN=$(aws sns create-platform-endpoint \ + --platform-application-arn $APP_ARN \ + --token ios-device-token-abc \ + --endpoint-url http://localhost:4566 --query EndpointArn --output text) + +# Plain string payload +aws sns publish --target-arn $ENDPOINT_ARN --message '{"aps":{"alert":"hi"}}' \ + --endpoint-url http://localhost:4566 + +# Platform-specific payloads with MessageStructure=json +aws sns publish --target-arn $ENDPOINT_ARN --message-structure json \ + --message '{"default":"fallback","APNS":"{\"aps\":{\"alert\":\"ios\"}}","GCM":"{\"notification\":{\"body\":\"android\"}}"}' \ + --endpoint-url http://localhost:4566 +``` + +When `MessageStructure="json"`, Floci picks the key matching the endpoint's platform +(`APNS`, `APNS_SANDBOX`, `GCM`, or `FCM`), falling back to `default`. The envelope +must be a JSON object and must include `default` — otherwise `InvalidParameter`. + +### Inspecting captured pushes + +```bash +# All captured pushes (newest first), or filtered by endpoint +curl http://localhost:4566/_aws/sns/push-notifications +curl "http://localhost:4566/_aws/sns/push-notifications?EndpointArn=$ENDPOINT_ARN" + +# Reset between tests +curl -X DELETE http://localhost:4566/_aws/sns/push-notifications +``` + +### Simulating expired tokens + +Two ways to make `Publish` fail with `EndpointDisabledException`: + +1. **Explicit** — call `SetEndpointAttributes` with `Enabled=false`. Matches the + real AWS flow after an async APNS/FCM failure. +2. **Sentinel** — create an endpoint whose token contains `EXPIRED` + (case-insensitive). Floci marks it `Enabled=false` on creation, so the first + publish fails. Lets you exercise the unhappy path with a single API call. + +### Error codes + +| Action | Condition | Error code | HTTP | +|---|---|---|---| +| `CreatePlatformApplication` | Missing `Name` | `InvalidParameter` | 400 | +| `CreatePlatformApplication` | Unsupported `Platform` (e.g. `WNS`, `ADM`) | `InvalidParameter` | 400 | +| `CreatePlatformEndpoint` | Missing `Token` | `InvalidParameter` | 400 | +| `CreatePlatformEndpoint` | Unknown `PlatformApplicationArn` | `NotFound` | 404 | +| `CreatePlatformEndpoint` | Same `Token`, different `CustomUserData` or attrs | `InvalidParameter` | 400 | +| `CreatePlatformEndpoint` | Platform app disabled | `PlatformApplicationDisabledException` | 400 | +| `Publish` | Unknown endpoint ARN | `NotFound` | 404 | +| `Publish` | `TargetArn` is a platform application ARN | `InvalidParameter` | 400 | +| `Publish` | Endpoint `Enabled=false` | `EndpointDisabledException` | 400 | +| `Publish` | Platform application `Enabled=false` | `PlatformApplicationDisabledException` | 400 | +| `Publish` | `MessageStructure=json` missing `default` key | `InvalidParameter` | 400 | +| `Publish` | `MessageStructure=json` message is not valid JSON | `InvalidParameter` | 400 | +| `GetPlatformApplicationAttributes` | Unknown ARN | `NotFound` | 404 | +| `GetEndpointAttributes` | Unknown ARN | `NotFound` | 404 | +| `SetEndpointAttributes` | Unknown ARN | `NotFound` | 404 | + +`DeletePlatformApplication` and `DeleteEndpoint` are idempotent — they succeed +silently if the resource does not exist, matching real SNS behavior. \ No newline at end of file diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsJsonHandler.java index c42c035432..68f41ab927 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sns/SnsJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsJsonHandler.java @@ -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 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 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 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 attrs = jsonNodeToMap(request.path("Attributes")); + snsService.setPlatformApplicationAttributes(arn, attrs, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handleListPlatformApplications(String region) { + List 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 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 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 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 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 jsonNodeToMap(JsonNode node) { Map map = new HashMap<>(); if (node != null && node.isObject()) { diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsPushInspectionController.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsPushInspectionController.java new file mode 100644 index 0000000000..91d5b55fbd --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsPushInspectionController.java @@ -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 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 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(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsQueryHandler.java index 8a3aea1610..52c95c69c9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sns/SnsQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsQueryHandler.java @@ -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 params, String region) { + String name = getParam(params, "Name"); + String platform = getParam(params, "Platform"); + Map 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 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 params, String region) { + String arn = getParam(params, "PlatformApplicationArn"); + try { + Map 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 params, String region) { + String arn = getParam(params, "PlatformApplicationArn"); + Map 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 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 params, String region) { + String appArn = getParam(params, "PlatformApplicationArn"); + String token = getParam(params, "Token"); + String customUserData = getParam(params, "CustomUserData"); + Map 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 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 params, String region) { + String arn = getParam(params, "EndpointArn"); + try { + Map 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 params, String region) { + String arn = getParam(params, "EndpointArn"); + Map 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 params, String region) { + String appArn = getParam(params, "PlatformApplicationArn"); + try { + List 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 params, String region) { String topicArn = getParam(params, "TopicArn"); List> entries = new ArrayList<>(); 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 c000198b2d..fd59c8c91e 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 @@ -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 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 SUPPORTED_PUSH_PLATFORMS = Set.of( + "APNS", "APNS_SANDBOX", "GCM", "FCM"); private final StorageBackend topicStore; private final StorageBackend subscriptionStore; + private final StorageBackend platformAppStore; + private final StorageBackend platformEndpointStore; + private final Deque 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>() { }), + storageFactory.create("sns", "sns-platform-applications.json", + new TypeReference>() { + }), + storageFactory.create("sns", "sns-platform-endpoints.json", + new TypeReference>() { + }), regionResolver, sqsService, lambdaService, @@ -87,8 +106,22 @@ public class SnsService { StorageBackend 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 topicStore, + StorageBackend subscriptionStore, + StorageBackend platformAppStore, + StorageBackend 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 topicStore, StorageBackend subscriptionStore, + StorageBackend platformAppStore, + StorageBackend 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 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 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 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 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 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 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 listPlatformApplications(String region) { + String prefix = "app::" + region + "::"; + return platformAppStore.scan(k -> k.startsWith(prefix)); + } + + public PlatformEndpoint createPlatformEndpoint(String platformApplicationArn, String token, + String customUserData, Map 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 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 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 listEndpointsByPlatformApplication(String platformApplicationArn, String region) { + String prefix = "endpoint::" + region + "::"; + List 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 peekPushNotifications(String endpointArn) { + List 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 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 requested) { + for (Map.Entry 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 getSubscriptionAttributes(String subscriptionArn, String region) { String key = subKey(region, subscriptionArn); Subscription sub = subscriptionStore.get(key) diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/model/PlatformApplication.java b/src/main/java/io/github/hectorvent/floci/services/sns/model/PlatformApplication.java new file mode 100644 index 0000000000..0740be96ea --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/sns/model/PlatformApplication.java @@ -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 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 getAttributes() { return attributes; } + public void setAttributes(Map attributes) { this.attributes = attributes; } + + public Instant getCreatedAt() { return createdAt; } + public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/model/PlatformEndpoint.java b/src/main/java/io/github/hectorvent/floci/services/sns/model/PlatformEndpoint.java new file mode 100644 index 0000000000..4eed9fa3a4 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/sns/model/PlatformEndpoint.java @@ -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 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 getAttributes() { return attributes; } + public void setAttributes(Map attributes) { this.attributes = attributes; } + + public Instant getCreatedAt() { return createdAt; } + public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/model/PushNotification.java b/src/main/java/io/github/hectorvent/floci/services/sns/model/PushNotification.java new file mode 100644 index 0000000000..2f88588f76 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/sns/model/PushNotification.java @@ -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 messageAttributes, + String messageId, + Instant timestamp +) {} 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 new file mode 100644 index 0000000000..dfa7f54ca1 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/sns/SnsMobilePushTest.java @@ -0,0 +1,344 @@ +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 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.*; + +/** + * Covers Floci's mock SNS mobile push surface: iOS (APNS / APNS_SANDBOX), Android + * (GCM / FCM), and the error codes the real AWS SNS API returns for push. + */ +class SnsMobilePushTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + + private SnsService snsService; + + @BeforeEach + void setUp() { + RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT); + snsService = new SnsService( + new InMemoryStorage<>(), + new InMemoryStorage<>(), + new InMemoryStorage<>(), + new InMemoryStorage<>(), + regionResolver, + null, + null); + } + + // --- CreatePlatformApplication --- + + @Test + void createPlatformApplication_apnsReturnsArn() { + PlatformApplication app = snsService.createPlatformApplication( + "ios-app", "APNS", Map.of("PlatformCredential", "fake-cert"), REGION); + assertEquals("arn:aws:sns:us-east-1:000000000000:app/APNS/ios-app", app.getArn()); + assertEquals("APNS", app.getPlatform()); + assertEquals("true", app.getAttributes().get("Enabled")); + } + + @Test + void createPlatformApplication_gcmReturnsArn() { + PlatformApplication app = snsService.createPlatformApplication( + "android-app", "GCM", Map.of("PlatformCredential", "fake-key"), REGION); + assertEquals("arn:aws:sns:us-east-1:000000000000:app/GCM/android-app", app.getArn()); + } + + @Test + void createPlatformApplication_rejectsUnsupportedPlatform() { + AwsException e = assertThrows(AwsException.class, + () -> snsService.createPlatformApplication("desktop", "WNS", Map.of(), REGION)); + assertEquals("InvalidParameter", e.getErrorCode()); + assertEquals(400, e.getHttpStatus()); + } + + @Test + void createPlatformApplication_requiresName() { + AwsException e = assertThrows(AwsException.class, + () -> snsService.createPlatformApplication("", "APNS", Map.of(), REGION)); + assertEquals("InvalidParameter", e.getErrorCode()); + } + + @Test + void createPlatformApplication_idempotentByName() { + PlatformApplication first = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + PlatformApplication second = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + assertEquals(first.getArn(), second.getArn()); + } + + // --- CreatePlatformEndpoint --- + + @Test + void createPlatformEndpoint_iosReturnsEndpointArn() { + PlatformApplication app = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + PlatformEndpoint endpoint = snsService.createPlatformEndpoint( + app.getArn(), "ios-device-token-abc", "ios-user-42", Map.of(), REGION); + assertTrue(endpoint.getArn().startsWith("arn:aws:sns:us-east-1:000000000000:endpoint/APNS/ios-app/")); + assertEquals("ios-device-token-abc", endpoint.getToken()); + assertEquals("true", endpoint.getAttributes().get("Enabled")); + } + + @Test + void createPlatformEndpoint_androidReturnsEndpointArn() { + PlatformApplication app = snsService.createPlatformApplication("android-app", "GCM", Map.of(), REGION); + PlatformEndpoint endpoint = snsService.createPlatformEndpoint( + app.getArn(), "fcm-registration-token-xyz", null, Map.of(), REGION); + assertTrue(endpoint.getArn().contains(":endpoint/GCM/android-app/")); + } + + @Test + void createPlatformEndpoint_rejectsMissingToken() { + PlatformApplication app = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + AwsException e = assertThrows(AwsException.class, + () -> snsService.createPlatformEndpoint(app.getArn(), null, null, Map.of(), REGION)); + assertEquals("InvalidParameter", e.getErrorCode()); + } + + @Test + void createPlatformEndpoint_unknownApplicationArnReturnsNotFound() { + AwsException e = assertThrows(AwsException.class, + () -> snsService.createPlatformEndpoint( + "arn:aws:sns:us-east-1:000000000000:app/APNS/missing", + "token", null, Map.of(), REGION)); + assertEquals("NotFound", e.getErrorCode()); + assertEquals(404, e.getHttpStatus()); + } + + @Test + void createPlatformEndpoint_sameTokenSameDataReturnsExisting() { + PlatformApplication app = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + PlatformEndpoint first = snsService.createPlatformEndpoint(app.getArn(), "tok-1", "user-7", Map.of(), REGION); + PlatformEndpoint second = snsService.createPlatformEndpoint(app.getArn(), "tok-1", "user-7", Map.of(), REGION); + assertEquals(first.getArn(), second.getArn()); + } + + @Test + void createPlatformEndpoint_sameTokenDifferentDataRejected() { + PlatformApplication app = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + snsService.createPlatformEndpoint(app.getArn(), "tok-1", "user-7", Map.of(), REGION); + AwsException e = assertThrows(AwsException.class, + () -> snsService.createPlatformEndpoint(app.getArn(), "tok-1", "user-99", Map.of(), REGION)); + assertEquals("InvalidParameter", e.getErrorCode()); + assertTrue(e.getMessage().contains("already exists with the same Token")); + } + + @Test + void createPlatformEndpoint_rejectsWhenPlatformAppDisabled() { + PlatformApplication app = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + snsService.setPlatformApplicationAttributes(app.getArn(), Map.of("Enabled", "false"), REGION); + AwsException e = assertThrows(AwsException.class, + () -> snsService.createPlatformEndpoint(app.getArn(), "tok-1", null, Map.of(), REGION)); + assertEquals("PlatformApplicationDisabledException", e.getErrorCode()); + } + + // --- Publish: happy paths --- + + @Test + void publish_iosDirectToEndpointCapturesPayload() { + PlatformApplication app = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + PlatformEndpoint endpoint = snsService.createPlatformEndpoint( + app.getArn(), "ios-token", null, Map.of(), REGION); + + String messageId = snsService.publish(null, endpoint.getArn(), null, + "{\"aps\":{\"alert\":\"hi iOS\"}}", null, null, null, null, null, REGION); + assertNotNull(messageId); + + List captured = snsService.peekPushNotifications(endpoint.getArn()); + assertEquals(1, captured.size()); + assertEquals("APNS", captured.get(0).platform()); + assertEquals("ios-token", captured.get(0).token()); + assertTrue(captured.get(0).payload().contains("hi iOS")); + } + + @Test + void publish_androidDirectToEndpointCapturesPayload() { + PlatformApplication app = snsService.createPlatformApplication("android-app", "GCM", Map.of(), REGION); + PlatformEndpoint endpoint = snsService.createPlatformEndpoint( + app.getArn(), "fcm-token", null, Map.of(), REGION); + + String messageId = snsService.publish(null, endpoint.getArn(), null, + "{\"notification\":{\"body\":\"hi Android\"}}", null, null, null, null, null, REGION); + assertNotNull(messageId); + + List captured = snsService.peekPushNotifications(endpoint.getArn()); + assertEquals(1, captured.size()); + assertEquals("GCM", captured.get(0).platform()); + assertTrue(captured.get(0).payload().contains("hi Android")); + } + + @Test + void publish_jsonStructureResolvesPlatformSpecificPayload() { + PlatformApplication iosApp = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + PlatformApplication andApp = snsService.createPlatformApplication("android-app", "GCM", Map.of(), REGION); + PlatformEndpoint iosEndpoint = snsService.createPlatformEndpoint(iosApp.getArn(), "ios-token", null, Map.of(), REGION); + PlatformEndpoint andEndpoint = snsService.createPlatformEndpoint(andApp.getArn(), "fcm-token", null, Map.of(), REGION); + + String envelope = "{" + + "\"default\":\"plain fallback\"," + + "\"APNS\":\"{\\\"aps\\\":{\\\"alert\\\":\\\"ios body\\\"}}\"," + + "\"GCM\":\"{\\\"notification\\\":{\\\"body\\\":\\\"android body\\\"}}\"" + + "}"; + + snsService.publish(null, iosEndpoint.getArn(), null, envelope, null, "json", null, null, null, REGION); + snsService.publish(null, andEndpoint.getArn(), null, envelope, null, "json", null, null, null, REGION); + + assertTrue(snsService.peekPushNotifications(iosEndpoint.getArn()).get(0).payload().contains("ios body")); + assertTrue(snsService.peekPushNotifications(andEndpoint.getArn()).get(0).payload().contains("android body")); + } + + @Test + void publish_jsonStructureFallsBackToDefaultWhenPlatformKeyMissing() { + PlatformApplication app = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + PlatformEndpoint endpoint = snsService.createPlatformEndpoint(app.getArn(), "ios-token", null, Map.of(), REGION); + + snsService.publish(null, endpoint.getArn(), null, + "{\"default\":\"fallback\"}", null, "json", null, null, null, REGION); + assertEquals("fallback", snsService.peekPushNotifications(endpoint.getArn()).get(0).payload()); + } + + // --- Publish: error codes --- + + @Test + void publish_jsonStructureRejectsMissingDefaultKey() { + PlatformApplication app = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + PlatformEndpoint endpoint = snsService.createPlatformEndpoint(app.getArn(), "ios-token", null, Map.of(), REGION); + + AwsException e = assertThrows(AwsException.class, () -> snsService.publish( + null, endpoint.getArn(), null, "{\"APNS\":\"x\"}", null, "json", + null, null, null, REGION)); + assertEquals("InvalidParameter", e.getErrorCode()); + assertTrue(e.getMessage().contains("default")); + } + + @Test + void publish_jsonStructureRejectsInvalidJson() { + PlatformApplication app = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + PlatformEndpoint endpoint = snsService.createPlatformEndpoint(app.getArn(), "ios-token", null, Map.of(), REGION); + + AwsException e = assertThrows(AwsException.class, () -> snsService.publish( + null, endpoint.getArn(), null, "not json at all", null, "json", + null, null, null, REGION)); + assertEquals("InvalidParameter", e.getErrorCode()); + } + + @Test + void publish_disabledEndpointThrowsEndpointDisabledException() { + PlatformApplication app = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + PlatformEndpoint endpoint = snsService.createPlatformEndpoint(app.getArn(), "ios-token", null, Map.of(), REGION); + snsService.setEndpointAttributes(endpoint.getArn(), Map.of("Enabled", "false"), REGION); + + AwsException e = assertThrows(AwsException.class, () -> snsService.publish( + null, endpoint.getArn(), null, "hello", null, null, null, null, null, REGION)); + assertEquals("EndpointDisabledException", e.getErrorCode()); + assertEquals(400, e.getHttpStatus()); + assertTrue(snsService.peekPushNotifications(endpoint.getArn()).isEmpty()); + } + + @Test + void publish_expiredSentinelTokenCreatesDisabledEndpointAndPublishFails() { + PlatformApplication app = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + PlatformEndpoint endpoint = snsService.createPlatformEndpoint( + app.getArn(), "EXPIRED-ios-device", null, Map.of(), REGION); + assertEquals("false", endpoint.getAttributes().get("Enabled")); + + AwsException e = assertThrows(AwsException.class, () -> snsService.publish( + null, endpoint.getArn(), null, "hello", null, null, null, null, null, REGION)); + assertEquals("EndpointDisabledException", e.getErrorCode()); + } + + @Test + void publish_unknownEndpointArnReturnsNotFound() { + AwsException e = assertThrows(AwsException.class, () -> snsService.publish( + null, + "arn:aws:sns:us-east-1:000000000000:endpoint/APNS/missing/" + java.util.UUID.randomUUID(), + null, "hello", null, null, null, null, null, REGION)); + assertEquals("NotFound", e.getErrorCode()); + assertEquals(404, e.getHttpStatus()); + } + + @Test + void publish_platformApplicationArnAsTargetIsRejected() { + PlatformApplication app = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + AwsException e = assertThrows(AwsException.class, () -> snsService.publish( + null, app.getArn(), null, "hello", null, null, null, null, null, REGION)); + assertEquals("InvalidParameter", e.getErrorCode()); + } + + @Test + void publish_disabledPlatformApplicationThrowsForEnabledEndpoint() { + PlatformApplication app = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + PlatformEndpoint endpoint = snsService.createPlatformEndpoint(app.getArn(), "ios-token", null, Map.of(), REGION); + snsService.setPlatformApplicationAttributes(app.getArn(), Map.of("Enabled", "false"), REGION); + + AwsException e = assertThrows(AwsException.class, () -> snsService.publish( + null, endpoint.getArn(), null, "hello", null, null, null, null, null, REGION)); + assertEquals("PlatformApplicationDisabledException", e.getErrorCode()); + } + + // --- Inspection helpers --- + + @Test + void peekPushNotifications_filtersByEndpointArn() { + PlatformApplication app = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + PlatformEndpoint a = snsService.createPlatformEndpoint(app.getArn(), "tok-a", null, Map.of(), REGION); + PlatformEndpoint b = snsService.createPlatformEndpoint(app.getArn(), "tok-b", null, Map.of(), REGION); + snsService.publish(null, a.getArn(), null, "to-a", null, null, null, null, null, REGION); + snsService.publish(null, b.getArn(), null, "to-b", null, null, null, null, null, REGION); + snsService.publish(null, a.getArn(), null, "to-a-again", null, null, null, null, null, REGION); + + assertEquals(2, snsService.peekPushNotifications(a.getArn()).size()); + assertEquals(1, snsService.peekPushNotifications(b.getArn()).size()); + assertEquals(3, snsService.peekPushNotifications(null).size()); + + snsService.clearPushNotifications(); + assertTrue(snsService.peekPushNotifications(null).isEmpty()); + } + + // --- Endpoint lifecycle --- + + @Test + void deleteEndpoint_isIdempotent() { + assertDoesNotThrow(() -> snsService.deleteEndpoint( + "arn:aws:sns:us-east-1:000000000000:endpoint/APNS/x/" + java.util.UUID.randomUUID(), REGION)); + } + + @Test + void getEndpointAttributes_returnsTokenEnabledAndCustomData() { + PlatformApplication app = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + PlatformEndpoint endpoint = snsService.createPlatformEndpoint(app.getArn(), "ios-token", "user-42", Map.of(), REGION); + + Map attrs = snsService.getEndpointAttributes(endpoint.getArn(), REGION); + assertEquals("ios-token", attrs.get("Token")); + assertEquals("user-42", attrs.get("CustomUserData")); + assertEquals("true", attrs.get("Enabled")); + } + + @Test + void listEndpointsByPlatformApplication_returnsAllEndpointsForApp() { + PlatformApplication app = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + snsService.createPlatformEndpoint(app.getArn(), "tok-1", null, Map.of(), REGION); + snsService.createPlatformEndpoint(app.getArn(), "tok-2", null, Map.of(), REGION); + assertEquals(2, snsService.listEndpointsByPlatformApplication(app.getArn(), REGION).size()); + } + + @Test + void deletePlatformApplication_cascadesEndpoints() { + PlatformApplication app = snsService.createPlatformApplication("ios-app", "APNS", Map.of(), REGION); + snsService.createPlatformEndpoint(app.getArn(), "tok-1", null, Map.of(), REGION); + snsService.deletePlatformApplication(app.getArn(), REGION); + assertTrue(snsService.listEndpointsByPlatformApplication(app.getArn(), REGION).isEmpty()); + assertTrue(snsService.listPlatformApplications(REGION).isEmpty()); + } +}