diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index 436d2c6591..948b7693da 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -33,6 +33,7 @@ import io.github.hectorvent.floci.services.oam.OamController; import io.github.hectorvent.floci.services.cloudfront.CloudFrontController; import io.github.hectorvent.floci.services.cloudfront.CloudFrontServingController; import io.github.hectorvent.floci.services.route53.Route53Controller; +import io.github.hectorvent.floci.services.ses.SesContactController; import io.github.hectorvent.floci.services.ses.SesController; import io.github.hectorvent.floci.services.ses.SesTemplateController; import io.github.hectorvent.floci.services.appsync.AppSyncController; @@ -286,7 +287,8 @@ public class ResolvedServiceCatalog { "ses", config.storage().mode(), 5000L, AwsNamespaces.SES, ServiceProtocol.REST_JSON, protocols(ServiceProtocol.REST_JSON, ServiceProtocol.QUERY), Set.of(), Set.of("email", "ses", "sesv2"), Set.of(), - Set.of(SesController.class, SesTemplateController.class)), + Set.of(SesController.class, SesContactController.class, + SesTemplateController.class)), descriptor("es", "opensearch", config.services().opensearch().enabled(), true, "opensearch", storageMode(config.storage().services().opensearch().mode(), config.storage().mode()), config.storage().services().opensearch().flushIntervalMs(), null, ServiceProtocol.REST_JSON, diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesContactController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesContactController.java new file mode 100644 index 0000000000..b9ccf0475d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesContactController.java @@ -0,0 +1,387 @@ +package io.github.hectorvent.floci.services.ses; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +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.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.ses.model.Contact; +import io.github.hectorvent.floci.services.ses.model.ContactList; +import io.github.hectorvent.floci.services.ses.model.Tag; +import io.github.hectorvent.floci.services.ses.model.Topic; +import io.github.hectorvent.floci.services.ses.model.TopicPreference; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import org.jboss.logging.Logger; + +import java.util.ArrayList; +import java.util.List; + +import static io.github.hectorvent.floci.services.ses.SesV2Json.coerceBoolean; +import static io.github.hectorvent.floci.services.ses.SesV2Json.parseTagsArray; +import static io.github.hectorvent.floci.services.ses.SesV2Json.remapV1Exception; +import static io.github.hectorvent.floci.services.ses.SesV2Json.requireJsonObject; +import static io.github.hectorvent.floci.services.ses.SesV2Json.unexpectedStartError; + +/** + * SES V2 contact-list and contact endpoints ({@code /v2/email/contact-lists}), split out of + * {@link SesController}. Every operation is a single-domain call on {@link SesContactService}, so + * this controller does not touch the {@link SesService} facade at all; the send-path opt-out + * collection that also reads contacts stays behind the facade. + */ +@Path("/v2/email") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class SesContactController { + + private static final Logger LOG = Logger.getLogger(SesContactController.class); + + private final SesContactService contactService; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public SesContactController(SesContactService contactService, RegionResolver regionResolver, + ObjectMapper objectMapper) { + this.contactService = contactService; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + @POST + @Path("/contact-lists") + public Response createContactList(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + try { + if (body == null || body.isBlank()) { + throw new AwsException("BadRequestException", "Request body is required.", 400); + } + JsonNode request = objectMapper.readTree(body); + requireJsonObject(request); + // Read leniently; the service surfaces a missing ContactListName as the AWS Smithy + // validation error rather than a custom "required" message. + String name = request.path("ContactListName").asText(null); + List topics = parseTopicsArray(request.path("Topics")); + List tags = parseTagsArray(request.path("Tags")); + String description = request.path("Description").asText(null); + contactService.createContactList(name, description, topics, tags, region); + LOG.infov("SES V2 CreateContactList: {0}", name); + return Response.ok(objectMapper.createObjectNode()).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (JsonProcessingException e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + + @GET + @Path("/contact-lists") + public Response listContactLists(@Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + ObjectNode result = objectMapper.createObjectNode(); + ArrayNode lists = result.putArray("ContactLists"); + for (ContactList cl : contactService.listContactLists(region)) { + ObjectNode item = lists.addObject(); + item.put("ContactListName", cl.getContactListName()); + if (cl.getLastUpdatedTimestamp() != null) { + item.put("LastUpdatedTimestamp", cl.getLastUpdatedTimestamp().getEpochSecond()); + } + } + return Response.ok(result).build(); + } + + @GET + @Path("/contact-lists/{contactListName}") + public Response getContactList(@Context HttpHeaders headers, + @PathParam("contactListName") String contactListName) { + String region = regionResolver.resolveRegion(headers); + return Response.ok(contactListJson(contactService.getContactList(contactListName, region))) + .build(); + } + + @PUT + @Path("/contact-lists/{contactListName}") + public Response updateContactList(@Context HttpHeaders headers, + @PathParam("contactListName") String contactListName, + String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode request = (body == null || body.isBlank()) + ? objectMapper.createObjectNode() + : objectMapper.readTree(body); + requireJsonObject(request); + JsonNode topicsNode = request.path("Topics"); + // Treat absent or explicit-null Topics as "not provided" (keep existing), consistent + // with Description; clearing is done via an explicit empty array []. + List topics = (topicsNode.isMissingNode() || topicsNode.isNull()) + ? null : parseTopicsArray(topicsNode); + JsonNode descNode = request.path("Description"); + boolean descriptionPresent = !descNode.isMissingNode() && !descNode.isNull(); + String description = descNode.asText(null); + contactService.updateContactList(contactListName, description, descriptionPresent, + topics, region); + LOG.infov("SES V2 UpdateContactList: {0}", contactListName); + return Response.ok(objectMapper.createObjectNode()).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (JsonProcessingException e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + + @DELETE + @Path("/contact-lists/{contactListName}") + public Response deleteContactList(@Context HttpHeaders headers, + @PathParam("contactListName") String contactListName) { + String region = regionResolver.resolveRegion(headers); + contactService.deleteContactList(contactListName, region); + LOG.infov("SES V2 DeleteContactList: {0}", contactListName); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private List parseTopicsArray(JsonNode topicsNode) { + List out = new ArrayList<>(); + if (topicsNode == null || topicsNode.isMissingNode() || topicsNode.isNull()) { + return out; + } + if (!topicsNode.isArray()) { + throw new AwsException("BadRequestException", "Topics must be an array.", 400); + } + for (JsonNode t : topicsNode) { + out.add(new Topic( + t.path("TopicName").asText(null), + t.path("DisplayName").asText(null), + t.path("DefaultSubscriptionStatus").asText(null), + t.path("Description").asText(null))); + } + return out; + } + + private ObjectNode contactListJson(ContactList cl) { + ObjectNode result = objectMapper.createObjectNode(); + result.put("ContactListName", cl.getContactListName()); + if (cl.getDescription() != null) { + result.put("Description", cl.getDescription()); + } + ArrayNode topics = result.putArray("Topics"); + for (Topic t : cl.getTopics()) { + ObjectNode to = topics.addObject(); + to.put("TopicName", t.getTopicName()); + to.put("DisplayName", t.getDisplayName()); + to.put("DefaultSubscriptionStatus", t.getDefaultSubscriptionStatus()); + if (t.getDescription() != null) { + to.put("Description", t.getDescription()); + } + } + if (cl.getCreatedTimestamp() != null) { + result.put("CreatedTimestamp", cl.getCreatedTimestamp().getEpochSecond()); + } + if (cl.getLastUpdatedTimestamp() != null) { + result.put("LastUpdatedTimestamp", cl.getLastUpdatedTimestamp().getEpochSecond()); + } + ArrayNode tags = result.putArray("Tags"); + for (Tag tag : cl.getTags()) { + ObjectNode tn = tags.addObject(); + tn.put("Key", tag.key()); + tn.put("Value", tag.value()); + } + return result; + } + + @POST + @Path("/contact-lists/{contactListName}/contacts") + public Response createContact(@Context HttpHeaders headers, + @PathParam("contactListName") String contactListName, String body) { + String region = regionResolver.resolveRegion(headers); + try { + if (body == null || body.isBlank()) { + throw new AwsException("BadRequestException", "Request body is required.", 400); + } + JsonNode request = objectMapper.readTree(body); + requireJsonObject(request); + String emailAddress = request.path("EmailAddress").asText(null); + List prefs = parseTopicPreferences(request.path("TopicPreferences")); + Boolean unsubscribeAll = parseUnsubscribeAll(request); + String attributesData = parseAttributesData(request); + contactService.createContact(contactListName, emailAddress, prefs, unsubscribeAll, + attributesData, region); + LOG.infov("SES V2 CreateContact: {0} in {1}", emailAddress, contactListName); + return Response.ok(objectMapper.createObjectNode()).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (JsonProcessingException e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + + @POST + @Path("/contact-lists/{contactListName}/contacts/list") + public Response listContacts(@Context HttpHeaders headers, + @PathParam("contactListName") String contactListName, String body) { + // AWS uses POST .../contacts/list with Filter/PageSize/NextToken in the body; Floci returns + // all contacts (filtering/pagination not yet implemented) but still rejects a malformed or + // non-object body like the other v2 endpoints. + String region = regionResolver.resolveRegion(headers); + try { + if (body != null && !body.isBlank()) { + requireJsonObject(objectMapper.readTree(body)); + } + SesContactService.ContactsWithList listed = + contactService.listContacts(contactListName, region); + ObjectNode result = objectMapper.createObjectNode(); + ArrayNode arr = result.putArray("Contacts"); + for (Contact c : listed.contacts()) { + arr.add(contactJson(c, listed.list(), false)); + } + return Response.ok(result).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (JsonProcessingException e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + + @GET + @Path("/contact-lists/{contactListName}/contacts/{emailAddress}") + public Response getContact(@Context HttpHeaders headers, + @PathParam("contactListName") String contactListName, + @PathParam("emailAddress") String emailAddress) { + String region = regionResolver.resolveRegion(headers); + SesContactService.ContactWithList result = + contactService.getContact(contactListName, emailAddress, region); + return Response.ok(contactJson(result.contact(), result.list(), true)).build(); + } + + @PUT + @Path("/contact-lists/{contactListName}/contacts/{emailAddress}") + public Response updateContact(@Context HttpHeaders headers, + @PathParam("contactListName") String contactListName, + @PathParam("emailAddress") String emailAddress, String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode request = (body == null || body.isBlank()) + ? objectMapper.createObjectNode() + : objectMapper.readTree(body); + requireJsonObject(request); + JsonNode prefsNode = request.path("TopicPreferences"); + boolean prefsPresent = !prefsNode.isMissingNode() && !prefsNode.isNull(); + List prefs = prefsPresent ? parseTopicPreferences(prefsNode) : null; + Boolean unsubscribeAll = parseUnsubscribeAll(request); + String attributesData = parseAttributesData(request); + contactService.updateContact(contactListName, emailAddress, prefs, prefsPresent, + unsubscribeAll, attributesData, region); + LOG.infov("SES V2 UpdateContact: {0} in {1}", emailAddress, contactListName); + return Response.ok(objectMapper.createObjectNode()).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (JsonProcessingException e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + + @DELETE + @Path("/contact-lists/{contactListName}/contacts/{emailAddress}") + public Response deleteContact(@Context HttpHeaders headers, + @PathParam("contactListName") String contactListName, + @PathParam("emailAddress") String emailAddress) { + String region = regionResolver.resolveRegion(headers); + contactService.deleteContact(contactListName, emailAddress, region); + LOG.infov("SES V2 DeleteContact: {0} in {1}", emailAddress, contactListName); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private List parseTopicPreferences(JsonNode node) { + if (node == null || node.isMissingNode() || node.isNull()) { + return null; + } + if (!node.isArray()) { + throw new AwsException("BadRequestException", "TopicPreferences must be an array.", 400); + } + List out = new ArrayList<>(); + for (JsonNode p : node) { + out.add(new TopicPreference( + p.path("TopicName").asText(null), + p.path("SubscriptionStatus").asText(null))); + } + return out; + } + + // UnsubscribeAll is a Boolean; AWS coerces it the same way as any other SES v2 boolean + // (see parseSendingEnabled): a JSON string coerces to true, a number/null/array/object is a + // SerializationException. Absent leaves it unset. + private static Boolean parseUnsubscribeAll(JsonNode request) { + if (!request.has("UnsubscribeAll")) { + return null; + } + return coerceBoolean(request.path("UnsubscribeAll")); + } + + // AttributesData is a String; a non-string (number/boolean/array/object) is a + // SerializationException. Absent or explicit null leaves it unset. + private static String parseAttributesData(JsonNode request) { + if (!request.has("AttributesData")) { + return null; + } + JsonNode node = request.path("AttributesData"); + if (node.isNull()) { + return null; + } + if (node.isTextual()) { + return node.textValue(); + } + if (node.isNumber()) { + throw new AwsException("SerializationException", + "NUMBER_VALUE can not be converted to a String", 400); + } + if (node.isBoolean()) { + throw new AwsException("SerializationException", + (node.booleanValue() ? "TRUE_VALUE" : "FALSE_VALUE") + + " can not be converted to a String", 400); + } + throw unexpectedStartError(node); + } + + private ObjectNode contactJson(Contact c, ContactList list, boolean full) { + ObjectNode result = objectMapper.createObjectNode(); + if (full) { + result.put("ContactListName", list.getContactListName()); + } + result.put("EmailAddress", c.getEmailAddress()); + ArrayNode prefs = result.putArray("TopicPreferences"); + for (TopicPreference p : c.getTopicPreferences()) { + ObjectNode po = prefs.addObject(); + po.put("TopicName", p.getTopicName()); + po.put("SubscriptionStatus", p.getSubscriptionStatus()); + } + ArrayNode defaults = result.putArray("TopicDefaultPreferences"); + for (TopicPreference p : contactService.deriveTopicDefaultPreferences(c, list)) { + ObjectNode po = defaults.addObject(); + po.put("TopicName", p.getTopicName()); + po.put("SubscriptionStatus", p.getSubscriptionStatus()); + } + result.put("UnsubscribeAll", c.isUnsubscribeAll()); + if (full && c.getAttributesData() != null) { + result.put("AttributesData", c.getAttributesData()); + } + if (full && c.getCreatedTimestamp() != null) { + result.put("CreatedTimestamp", c.getCreatedTimestamp().getEpochSecond()); + } + if (c.getLastUpdatedTimestamp() != null) { + result.put("LastUpdatedTimestamp", c.getLastUpdatedTimestamp().getEpochSecond()); + } + return result; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java index cfdd546481..efba63cdcb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java @@ -10,12 +10,8 @@ import io.github.hectorvent.floci.services.ses.model.GuardianOptions; import io.github.hectorvent.floci.services.ses.model.BulkEmailEntry; import io.github.hectorvent.floci.services.ses.model.BulkEmailEntryResult; import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; -import io.github.hectorvent.floci.services.ses.model.Contact; -import io.github.hectorvent.floci.services.ses.model.ContactList; import io.github.hectorvent.floci.services.ses.model.CustomVerificationEmailTemplate; import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool; -import io.github.hectorvent.floci.services.ses.model.Topic; -import io.github.hectorvent.floci.services.ses.model.TopicPreference; import io.github.hectorvent.floci.services.ses.model.DeliveryOptions; import io.github.hectorvent.floci.services.ses.model.EmailTemplate; import io.github.hectorvent.floci.services.ses.model.EventDestination; @@ -1682,50 +1678,6 @@ public class SesController { return Response.ok(objectMapper.createObjectNode()).build(); } - // ─────────────────────────── Contact lists ─────────────────────────── - - @POST - @Path("/contact-lists") - public Response createContactList(@Context HttpHeaders headers, String body) { - String region = regionResolver.resolveRegion(headers); - try { - if (body == null || body.isBlank()) { - throw new AwsException("BadRequestException", "Request body is required.", 400); - } - JsonNode request = objectMapper.readTree(body); - requireJsonObject(request); - // Read leniently; the service surfaces a missing ContactListName as the AWS Smithy - // validation error rather than a custom "required" message. - String name = request.path("ContactListName").asText(null); - List topics = parseTopicsArray(request.path("Topics")); - List tags = parseTagsArray(request.path("Tags")); - String description = request.path("Description").asText(null); - sesService.createContactList(name, description, topics, tags, region); - LOG.infov("SES V2 CreateContactList: {0}", name); - return Response.ok(objectMapper.createObjectNode()).build(); - } catch (AwsException e) { - throw remapV1Exception(e); - } catch (com.fasterxml.jackson.core.JsonProcessingException e) { - throw new AwsException("BadRequestException", e.getMessage(), 400); - } - } - - @GET - @Path("/contact-lists") - public Response listContactLists(@Context HttpHeaders headers) { - String region = regionResolver.resolveRegion(headers); - ObjectNode result = objectMapper.createObjectNode(); - ArrayNode lists = result.putArray("ContactLists"); - for (ContactList cl : sesService.listContactLists(region)) { - ObjectNode item = lists.addObject(); - item.put("ContactListName", cl.getContactListName()); - if (cl.getLastUpdatedTimestamp() != null) { - item.put("LastUpdatedTimestamp", cl.getLastUpdatedTimestamp().getEpochSecond()); - } - } - return Response.ok(result).build(); - } - @PUT @Path("/dedicated-ip-pools/{poolName}/scaling") public Response putDedicatedIpPoolScalingAttributes(@Context HttpHeaders headers, @@ -1756,285 +1708,6 @@ public class SesController { return Response.ok(result).build(); } - @GET - @Path("/contact-lists/{contactListName}") - public Response getContactList(@Context HttpHeaders headers, - @PathParam("contactListName") String contactListName) { - String region = regionResolver.resolveRegion(headers); - return Response.ok(contactListJson(sesService.getContactList(contactListName, region))).build(); - } - - @PUT - @Path("/contact-lists/{contactListName}") - public Response updateContactList(@Context HttpHeaders headers, - @PathParam("contactListName") String contactListName, - String body) { - String region = regionResolver.resolveRegion(headers); - try { - JsonNode request = (body == null || body.isBlank()) - ? objectMapper.createObjectNode() - : objectMapper.readTree(body); - requireJsonObject(request); - JsonNode topicsNode = request.path("Topics"); - // Treat absent or explicit-null Topics as "not provided" (keep existing), consistent - // with Description; clearing is done via an explicit empty array []. - List topics = (topicsNode.isMissingNode() || topicsNode.isNull()) - ? null : parseTopicsArray(topicsNode); - JsonNode descNode = request.path("Description"); - boolean descriptionPresent = !descNode.isMissingNode() && !descNode.isNull(); - String description = descNode.asText(null); - sesService.updateContactList(contactListName, description, descriptionPresent, topics, region); - LOG.infov("SES V2 UpdateContactList: {0}", contactListName); - return Response.ok(objectMapper.createObjectNode()).build(); - } catch (AwsException e) { - throw remapV1Exception(e); - } catch (com.fasterxml.jackson.core.JsonProcessingException e) { - throw new AwsException("BadRequestException", e.getMessage(), 400); - } - } - - @DELETE - @Path("/contact-lists/{contactListName}") - public Response deleteContactList(@Context HttpHeaders headers, - @PathParam("contactListName") String contactListName) { - String region = regionResolver.resolveRegion(headers); - sesService.deleteContactList(contactListName, region); - LOG.infov("SES V2 DeleteContactList: {0}", contactListName); - return Response.ok(objectMapper.createObjectNode()).build(); - } - - private List parseTopicsArray(JsonNode topicsNode) { - List out = new ArrayList<>(); - if (topicsNode == null || topicsNode.isMissingNode() || topicsNode.isNull()) { - return out; - } - if (!topicsNode.isArray()) { - throw new AwsException("BadRequestException", "Topics must be an array.", 400); - } - for (JsonNode t : topicsNode) { - out.add(new Topic( - t.path("TopicName").asText(null), - t.path("DisplayName").asText(null), - t.path("DefaultSubscriptionStatus").asText(null), - t.path("Description").asText(null))); - } - return out; - } - - private ObjectNode contactListJson(ContactList cl) { - ObjectNode result = objectMapper.createObjectNode(); - result.put("ContactListName", cl.getContactListName()); - if (cl.getDescription() != null) { - result.put("Description", cl.getDescription()); - } - ArrayNode topics = result.putArray("Topics"); - for (Topic t : cl.getTopics()) { - ObjectNode to = topics.addObject(); - to.put("TopicName", t.getTopicName()); - to.put("DisplayName", t.getDisplayName()); - to.put("DefaultSubscriptionStatus", t.getDefaultSubscriptionStatus()); - if (t.getDescription() != null) { - to.put("Description", t.getDescription()); - } - } - if (cl.getCreatedTimestamp() != null) { - result.put("CreatedTimestamp", cl.getCreatedTimestamp().getEpochSecond()); - } - if (cl.getLastUpdatedTimestamp() != null) { - result.put("LastUpdatedTimestamp", cl.getLastUpdatedTimestamp().getEpochSecond()); - } - ArrayNode tags = result.putArray("Tags"); - for (Tag tag : cl.getTags()) { - ObjectNode tn = tags.addObject(); - tn.put("Key", tag.key()); - tn.put("Value", tag.value()); - } - return result; - } - - // ───────────────────────────── Contacts ───────────────────────────── - - @POST - @Path("/contact-lists/{contactListName}/contacts") - public Response createContact(@Context HttpHeaders headers, - @PathParam("contactListName") String contactListName, String body) { - String region = regionResolver.resolveRegion(headers); - try { - if (body == null || body.isBlank()) { - throw new AwsException("BadRequestException", "Request body is required.", 400); - } - JsonNode request = objectMapper.readTree(body); - requireJsonObject(request); - String emailAddress = request.path("EmailAddress").asText(null); - List prefs = parseTopicPreferences(request.path("TopicPreferences")); - Boolean unsubscribeAll = parseUnsubscribeAll(request); - String attributesData = parseAttributesData(request); - sesService.createContact(contactListName, emailAddress, prefs, unsubscribeAll, attributesData, region); - LOG.infov("SES V2 CreateContact: {0} in {1}", emailAddress, contactListName); - return Response.ok(objectMapper.createObjectNode()).build(); - } catch (AwsException e) { - throw remapV1Exception(e); - } catch (com.fasterxml.jackson.core.JsonProcessingException e) { - throw new AwsException("BadRequestException", e.getMessage(), 400); - } - } - - @POST - @Path("/contact-lists/{contactListName}/contacts/list") - public Response listContacts(@Context HttpHeaders headers, - @PathParam("contactListName") String contactListName, String body) { - // AWS uses POST .../contacts/list with Filter/PageSize/NextToken in the body; Floci returns - // all contacts (filtering/pagination not yet implemented) but still rejects a malformed or - // non-object body like the other v2 endpoints. - String region = regionResolver.resolveRegion(headers); - try { - if (body != null && !body.isBlank()) { - requireJsonObject(objectMapper.readTree(body)); - } - SesContactService.ContactsWithList listed = sesService.listContacts(contactListName, region); - ObjectNode result = objectMapper.createObjectNode(); - ArrayNode arr = result.putArray("Contacts"); - for (Contact c : listed.contacts()) { - arr.add(contactJson(c, listed.list(), false)); - } - return Response.ok(result).build(); - } catch (AwsException e) { - throw remapV1Exception(e); - } catch (com.fasterxml.jackson.core.JsonProcessingException e) { - throw new AwsException("BadRequestException", e.getMessage(), 400); - } - } - - @GET - @Path("/contact-lists/{contactListName}/contacts/{emailAddress}") - public Response getContact(@Context HttpHeaders headers, - @PathParam("contactListName") String contactListName, - @PathParam("emailAddress") String emailAddress) { - String region = regionResolver.resolveRegion(headers); - SesContactService.ContactWithList result = sesService.getContact(contactListName, emailAddress, region); - return Response.ok(contactJson(result.contact(), result.list(), true)).build(); - } - - @PUT - @Path("/contact-lists/{contactListName}/contacts/{emailAddress}") - public Response updateContact(@Context HttpHeaders headers, - @PathParam("contactListName") String contactListName, - @PathParam("emailAddress") String emailAddress, String body) { - String region = regionResolver.resolveRegion(headers); - try { - JsonNode request = (body == null || body.isBlank()) - ? objectMapper.createObjectNode() - : objectMapper.readTree(body); - requireJsonObject(request); - JsonNode prefsNode = request.path("TopicPreferences"); - boolean prefsPresent = !prefsNode.isMissingNode() && !prefsNode.isNull(); - List prefs = prefsPresent ? parseTopicPreferences(prefsNode) : null; - Boolean unsubscribeAll = parseUnsubscribeAll(request); - String attributesData = parseAttributesData(request); - sesService.updateContact(contactListName, emailAddress, prefs, prefsPresent, - unsubscribeAll, attributesData, region); - LOG.infov("SES V2 UpdateContact: {0} in {1}", emailAddress, contactListName); - return Response.ok(objectMapper.createObjectNode()).build(); - } catch (AwsException e) { - throw remapV1Exception(e); - } catch (com.fasterxml.jackson.core.JsonProcessingException e) { - throw new AwsException("BadRequestException", e.getMessage(), 400); - } - } - - @DELETE - @Path("/contact-lists/{contactListName}/contacts/{emailAddress}") - public Response deleteContact(@Context HttpHeaders headers, - @PathParam("contactListName") String contactListName, - @PathParam("emailAddress") String emailAddress) { - String region = regionResolver.resolveRegion(headers); - sesService.deleteContact(contactListName, emailAddress, region); - LOG.infov("SES V2 DeleteContact: {0} in {1}", emailAddress, contactListName); - return Response.ok(objectMapper.createObjectNode()).build(); - } - - private List parseTopicPreferences(JsonNode node) { - if (node == null || node.isMissingNode() || node.isNull()) { - return null; - } - if (!node.isArray()) { - throw new AwsException("BadRequestException", "TopicPreferences must be an array.", 400); - } - List out = new ArrayList<>(); - for (JsonNode p : node) { - out.add(new TopicPreference( - p.path("TopicName").asText(null), - p.path("SubscriptionStatus").asText(null))); - } - return out; - } - - // UnsubscribeAll is a Boolean; AWS coerces it the same way as any other SES v2 boolean - // (see parseSendingEnabled): a JSON string coerces to true, a number/null/array/object is a - // SerializationException. Absent leaves it unset. - private static Boolean parseUnsubscribeAll(JsonNode request) { - if (!request.has("UnsubscribeAll")) { - return null; - } - return coerceBoolean(request.path("UnsubscribeAll")); - } - - // AttributesData is a String; a non-string (number/boolean/array/object) is a - // SerializationException. Absent or explicit null leaves it unset. - private static String parseAttributesData(JsonNode request) { - if (!request.has("AttributesData")) { - return null; - } - JsonNode node = request.path("AttributesData"); - if (node.isNull()) { - return null; - } - if (node.isTextual()) { - return node.textValue(); - } - if (node.isNumber()) { - throw new AwsException("SerializationException", - "NUMBER_VALUE can not be converted to a String", 400); - } - if (node.isBoolean()) { - throw new AwsException("SerializationException", - (node.booleanValue() ? "TRUE_VALUE" : "FALSE_VALUE") - + " can not be converted to a String", 400); - } - throw unexpectedStartError(node); - } - - private ObjectNode contactJson(Contact c, ContactList list, boolean full) { - ObjectNode result = objectMapper.createObjectNode(); - if (full) { - result.put("ContactListName", list.getContactListName()); - } - result.put("EmailAddress", c.getEmailAddress()); - ArrayNode prefs = result.putArray("TopicPreferences"); - for (TopicPreference p : c.getTopicPreferences()) { - ObjectNode po = prefs.addObject(); - po.put("TopicName", p.getTopicName()); - po.put("SubscriptionStatus", p.getSubscriptionStatus()); - } - ArrayNode defaults = result.putArray("TopicDefaultPreferences"); - for (TopicPreference p : sesService.deriveTopicDefaultPreferences(c, list)) { - ObjectNode po = defaults.addObject(); - po.put("TopicName", p.getTopicName()); - po.put("SubscriptionStatus", p.getSubscriptionStatus()); - } - result.put("UnsubscribeAll", c.isUnsubscribeAll()); - if (full && c.getAttributesData() != null) { - result.put("AttributesData", c.getAttributesData()); - } - if (full && c.getCreatedTimestamp() != null) { - result.put("CreatedTimestamp", c.getCreatedTimestamp().getEpochSecond()); - } - if (c.getLastUpdatedTimestamp() != null) { - result.put("LastUpdatedTimestamp", c.getLastUpdatedTimestamp().getEpochSecond()); - } - return result; - } - @GET @Path("/dedicated-ips/{ip}") public Response getDedicatedIp(@Context HttpHeaders headers, @PathParam("ip") String ip) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java index 6bec674f94..9c8fdaf31e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java @@ -13,7 +13,6 @@ import io.github.hectorvent.floci.services.ses.model.BulkEmailEntryResult; import io.github.hectorvent.floci.services.ses.model.CloudWatchDimensionConfiguration; import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; import io.github.hectorvent.floci.services.ses.model.Contact; -import io.github.hectorvent.floci.services.ses.model.ContactList; import io.github.hectorvent.floci.services.ses.model.CustomVerificationEmailTemplate; import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool; import io.github.hectorvent.floci.services.ses.model.DeliveryOptions; @@ -24,7 +23,6 @@ import io.github.hectorvent.floci.services.ses.model.ListManagementOptions; import io.github.hectorvent.floci.services.ses.model.MessageHeader; import io.github.hectorvent.floci.services.ses.model.MessageTag; import io.github.hectorvent.floci.services.ses.model.Topic; -import io.github.hectorvent.floci.services.ses.model.TopicPreference; import io.github.hectorvent.floci.services.ses.model.TrackingOptions; import io.github.hectorvent.floci.services.ses.model.VdmOptions; import io.github.hectorvent.floci.services.ses.model.SentEmail; @@ -83,8 +81,9 @@ public class SesService { private final SesSuppressionService suppressionService; // Dedicated IP pools extracted to SesDedicatedIpService. The facade delegates. private final SesDedicatedIpService dedicatedIpService; - // Contact lists and contacts (two stores) extracted to SesContactService. The - // facade delegates, and its send-path list-management orchestration calls into the service. + // Contact lists and contacts (two stores) live in SesContactService, which the v2 controller + // and the unsubscribe endpoint call directly; the facade only reaches it from the send-path + // list-management orchestration and the ARN-dispatched tagging. private final SesContactService contactService; // Identity (sending authorization) policy storage, extracted to SesPolicyService. // The facade keeps the identity-existence check and delegates the rest. @@ -1162,65 +1161,6 @@ public class SesService { dedicatedIpService.deleteDedicatedIpPool(poolName, region); } - - // Contact lists and contacts live in SesContactService; the facade forwards. - // Its send-path list-management (collectListManagementOptOuts) also calls into that service. - - public ContactList createContactList(String name, String description, List topics, - List tags, String region) { - return contactService.createContactList(name, description, topics, tags, region); - } - - public ContactList getContactList(String name, String region) { - return contactService.getContactList(name, region); - } - - public List listContactLists(String region) { - return contactService.listContactLists(region); - } - - public ContactList updateContactList(String name, String description, boolean descriptionPresent, - List topics, String region) { - return contactService.updateContactList(name, description, descriptionPresent, topics, region); - } - - public void deleteContactList(String name, String region) { - contactService.deleteContactList(name, region); - } - - public Contact createContact(String listName, String emailAddress, List topicPreferences, - Boolean unsubscribeAll, String attributesData, String region) { - return contactService.createContact(listName, emailAddress, topicPreferences, unsubscribeAll, - attributesData, region); - } - - public SesContactService.ContactWithList getContact(String listName, String emailAddress, String region) { - return contactService.getContact(listName, emailAddress, region); - } - - public SesContactService.ContactsWithList listContacts(String listName, String region) { - return contactService.listContacts(listName, region); - } - - public Contact updateContact(String listName, String emailAddress, List topicPreferences, - boolean topicPreferencesPresent, Boolean unsubscribeAll, String attributesData, - String region) { - return contactService.updateContact(listName, emailAddress, topicPreferences, topicPreferencesPresent, - unsubscribeAll, attributesData, region); - } - - public void deleteContact(String listName, String emailAddress, String region) { - contactService.deleteContact(listName, emailAddress, region); - } - - public List deriveTopicDefaultPreferences(Contact contact, ContactList list) { - return contactService.deriveTopicDefaultPreferences(contact, list); - } - - public void unsubscribeContact(String listName, String emailAddress, String topicName, String region) { - contactService.unsubscribeContact(listName, emailAddress, topicName, region); - } - // ──────────────── Identity (sending authorization) policies ──────────────── // One shared store behind the v1 (PutIdentityPolicy/GetIdentityPolicies/ListIdentityPolicies/ // DeleteIdentityPolicy) and v2 (Create/Get/Update/DeleteEmailIdentityPolicy) APIs. Verified diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesUnsubscribeController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesUnsubscribeController.java index a628b2976e..c037355d0d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesUnsubscribeController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesUnsubscribeController.java @@ -33,11 +33,11 @@ import java.nio.charset.StandardCharsets; @Path("/_aws/ses/unsubscribe") public class SesUnsubscribeController { - private final SesService sesService; + private final SesContactService contactService; @Inject - public SesUnsubscribeController(SesService sesService) { - this.sesService = sesService; + public SesUnsubscribeController(SesContactService contactService) { + this.contactService = contactService; } @GET @@ -79,7 +79,7 @@ public class SesUnsubscribeController { return invalid; } try { - sesService.unsubscribeContact(contactList, address, topic, region); + contactService.unsubscribeContact(contactList, address, topic, region); } catch (AwsException e) { return Response.status(e.getHttpStatus()).entity(e.getMessage()).build(); } diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceListManagementTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceListManagementTest.java index dfbf56b425..4f5acdf5f7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceListManagementTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceListManagementTest.java @@ -41,6 +41,7 @@ class SesServiceListManagementTest { @Mock SmtpRelay smtpRelay; private SesService service; + private SesContactService contacts; private InMemoryStorage contactStore; @BeforeEach @@ -48,17 +49,18 @@ class SesServiceListManagementTest { SesServiceTestBuilder builder = SesServiceTestBuilder.create().smtpRelay(smtpRelay); contactStore = builder.contactStore(); service = builder.build(); + contacts = builder.contactService(); // Sports defaults OPT_IN, Promos defaults OPT_OUT. - service.createContactList(LIST, "desc", List.of( + contacts.createContactList(LIST, "desc", List.of( new Topic("Sports", "Sports", "OPT_IN", "d"), new Topic("Promos", "Promos", "OPT_OUT", "d")), List.of(), REGION); - service.createContact(LIST, "unsub@example.com", List.of(), true, null, REGION); - service.createContact(LIST, "sportsout@example.com", + contacts.createContact(LIST, "unsub@example.com", List.of(), true, null, REGION); + contacts.createContact(LIST, "sportsout@example.com", List.of(new TopicPreference("Sports", "OPT_OUT")), false, null, REGION); - service.createContact(LIST, "sportsin@example.com", + contacts.createContact(LIST, "sportsin@example.com", List.of(new TopicPreference("Sports", "OPT_IN")), false, null, REGION); - service.createContact(LIST, "noprefs@example.com", List.of(), false, null, REGION); + contacts.createContact(LIST, "noprefs@example.com", List.of(), false, null, REGION); } private void send(List to, String topicName) { @@ -169,7 +171,7 @@ class SesServiceListManagementTest { @Test void unsubscribeContact_withTopic_setsOptOut() { - service.unsubscribeContact(LIST, "sportsin@example.com", "Sports", REGION); + contacts.unsubscribeContact(LIST, "sportsin@example.com", "Sports", REGION); Contact c = contact("sportsin@example.com"); assertTrue(c.getTopicPreferences().stream() .anyMatch(p -> "Sports".equals(p.getTopicName()) && "OPT_OUT".equals(p.getSubscriptionStatus()))); @@ -177,13 +179,13 @@ class SesServiceListManagementTest { @Test void unsubscribeContact_withoutTopic_setsUnsubscribeAll() { - service.unsubscribeContact(LIST, "sportsin@example.com", null, REGION); + contacts.unsubscribeContact(LIST, "sportsin@example.com", null, REGION); assertTrue(contact("sportsin@example.com").isUnsubscribeAll()); } @Test void unsubscribeContact_absentContact_autoCreatesAndOptsOut() { - service.unsubscribeContact(LIST, "ghost@example.com", null, REGION); + contacts.unsubscribeContact(LIST, "ghost@example.com", null, REGION); assertTrue(contact("ghost@example.com").isUnsubscribeAll()); } @@ -193,7 +195,7 @@ class SesServiceListManagementTest { c.setTopicPreferences(List.of(new TopicPreference("Sports", "OPT_IN"))); contactStore.put("contact::" + REGION + "::" + LIST + "::immutable@example.com", c); - service.unsubscribeContact(LIST, "immutable@example.com", "Promos", REGION); + contacts.unsubscribeContact(LIST, "immutable@example.com", "Promos", REGION); assertTrue(contact("immutable@example.com").getTopicPreferences().stream() .anyMatch(p -> "Promos".equals(p.getTopicName()) && "OPT_OUT".equals(p.getSubscriptionStatus()))); diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.java index 67639361a9..423027a14b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.java @@ -57,6 +57,9 @@ final class SesServiceTestBuilder { private Route53Service route53Service = null; private ObjectMapper objectMapper = new ObjectMapper(); private Clock clock = Clock.systemUTC(); + // Built by build(); exposed so tests can seed contacts through the domain service now that the + // facade no longer forwards the contact CRUD. + private SesContactService contactService; static SesServiceTestBuilder create() { return new SesServiceTestBuilder(); @@ -112,7 +115,15 @@ final class SesServiceTestBuilder { return contactListStore; } + SesContactService contactService() { + if (contactService == null) { + throw new IllegalStateException("call build() first"); + } + return contactService; + } + SesService build() { + contactService = new SesContactService(contactListStore, contactStore, clock); return new SesService( new SesIdentityService(identityStore, route53Service, clock), new SesSentEmailService(emailStore), @@ -121,7 +132,7 @@ final class SesServiceTestBuilder { new SesConfigurationSetService(configSetStore), new SesSuppressionService(suppressionStore, accountSuppressionStore, new InMemoryStorage<>()), new SesDedicatedIpService(dedicatedIpPoolStore), - new SesContactService(contactListStore, contactStore, clock), + contactService, new SesPolicyService(policyStore, objectMapper), new SesCvetService(cvetStore), new SesTenantService(tenantStore, tenantAssociationStore, clock, new SecureRandom()),