From 10f799a2b787cd07b1d5fd90e05b0e030dd6dbc6 Mon Sep 17 00:00:00 2001 From: Kenshin Okinaka Date: Sat, 11 Jul 2026 13:15:59 +0900 Subject: [PATCH] feat(ses): implement Contact CRUD for SES v2 (#1723) * feat(ses): implement Contact CRUD for SES v2 Add the SES v2 Contact APIs under /v2/email/contact-lists/{name}/contacts: CreateContact, GetContact, ListContacts (POST .../contacts/list), UpdateContact, DeleteContact. Contacts carry per-topic subscription preferences, an unsubscribe-all flag, and free-form attributes; TopicDefaultPreferences is derived at read time from the list's topics. Behaviour is verified against real AWS: validation order (Smithy enum -> EmailAddress format -> list existence -> topic existence), AlreadyExists / NotFound / invalid-topic / invalid-email error shapes, and the UpdateContact semantics (TopicPreferences merge by topic name; AttributesData and UnsubscribeAll replaced). Covered by a RestAssured integration test and an AWS Java SDK v2 compatibility test. * refactor(ses): resolve contact list once for reads and delete under lock Address review consistency findings on the Contact CRUD read/delete paths: - getContact/listContacts returned only the contact(s), so the controller fetched the ContactList a second time to render TopicDefaultPreferences. Between the two calls a concurrent delete could turn a successful read into a misleading "List not found". The service now returns the resolved list alongside the contact(s) (ContactWithList / ContactsWithList), so the read is a single, consistent lookup. - deleteContact re-checked list existence before acquiring contactMutationLock, unlike createContact/updateContact which re-check inside it. Move the getContactList check inside the lock so a concurrent deleteContactList surfaces "list not found" rather than "contact not found". --- .../java/com/floci/test/SesContactTest.java | 162 ++++++++ docs/services/ses.md | 5 + .../floci/services/ses/SesController.java | 203 +++++++++- .../floci/services/ses/SesService.java | 225 ++++++++++- .../floci/services/ses/model/Contact.java | 68 ++++ .../services/ses/model/TopicPreference.java | 37 ++ .../ses/SesContactV2IntegrationTest.java | 369 ++++++++++++++++++ .../ses/SesServiceDkimLookupCacheTest.java | 2 + .../ses/SesServiceLegacyDkimTokensTest.java | 2 + .../services/ses/SesServiceSmtpTest.java | 2 + .../SesServiceSuppressionLegacyKeyTest.java | 2 + .../ses/SesServiceSuppressionReasonTest.java | 2 + 12 files changed, 1069 insertions(+), 10 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesContactTest.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/ses/model/Contact.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/ses/model/TopicPreference.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ses/SesContactV2IntegrationTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesContactTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesContactTest.java new file mode 100644 index 0000000000..61b8a1a335 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesContactTest.java @@ -0,0 +1,162 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import software.amazon.awssdk.services.sesv2.SesV2Client; +import software.amazon.awssdk.services.sesv2.model.AlreadyExistsException; +import software.amazon.awssdk.services.sesv2.model.BadRequestException; +import software.amazon.awssdk.services.sesv2.model.CreateContactListRequest; +import software.amazon.awssdk.services.sesv2.model.CreateContactRequest; +import software.amazon.awssdk.services.sesv2.model.DeleteContactListRequest; +import software.amazon.awssdk.services.sesv2.model.DeleteContactRequest; +import software.amazon.awssdk.services.sesv2.model.GetContactRequest; +import software.amazon.awssdk.services.sesv2.model.GetContactResponse; +import software.amazon.awssdk.services.sesv2.model.NotFoundException; +import software.amazon.awssdk.services.sesv2.model.SubscriptionStatus; +import software.amazon.awssdk.services.sesv2.model.Topic; +import software.amazon.awssdk.services.sesv2.model.TopicPreference; +import software.amazon.awssdk.services.sesv2.model.UpdateContactRequest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * SDK compatibility test for the SES v2 Contact APIs (CreateContact / GetContact / + * ListContacts / UpdateContact / DeleteContact) against a live Floci instance: + * TopicDefaultPreferences derivation, duplicate/not-found/unknown-topic errors, + * and the AWS-verified update merge/replace semantics. + */ +@DisplayName("SES v2 Contacts") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesContactTest { + + private static final String LIST = "compat-contacts-list"; + private static final String EMAIL = "alice@example.com"; + + private static SesV2Client sesV2; + + @BeforeAll + static void setup() { + sesV2 = TestFixtures.sesV2Client(); + deleteAllContactLists(); + sesV2.createContactList(CreateContactListRequest.builder() + .contactListName(LIST) + .topics(Topic.builder().topicName("weekly").displayName("Weekly") + .defaultSubscriptionStatus(SubscriptionStatus.OPT_IN).build(), + Topic.builder().topicName("promos").displayName("Promos") + .defaultSubscriptionStatus(SubscriptionStatus.OPT_OUT).build()) + .build()); + } + + @AfterAll + static void cleanup() { + if (sesV2 != null) { + deleteAllContactLists(); + sesV2.close(); + } + } + + private static void deleteAllContactLists() { + // Only one contact list may exist per account; clear whatever is present (and its contacts). + sesV2.listContactLists(r -> {}).contactLists().forEach(cl -> { + String name = cl.contactListName(); + sesV2.listContacts(r -> r.contactListName(name)).contacts().forEach(c -> + sesV2.deleteContact(DeleteContactRequest.builder() + .contactListName(name).emailAddress(c.emailAddress()).build())); + sesV2.deleteContactList(DeleteContactListRequest.builder().contactListName(name).build()); + }); + } + + @Test + @Order(1) + void createContact_thenGet_derivesTopicDefaultPreferences() { + sesV2.createContact(CreateContactRequest.builder() + .contactListName(LIST).emailAddress(EMAIL) + .topicPreferences(TopicPreference.builder().topicName("weekly") + .subscriptionStatus(SubscriptionStatus.OPT_OUT).build()) + .attributesData("{\"name\":\"Alice\"}").unsubscribeAll(false).build()); + + GetContactResponse r = sesV2.getContact(GetContactRequest.builder() + .contactListName(LIST).emailAddress(EMAIL).build()); + assertThat(r.emailAddress()).isEqualTo(EMAIL); + assertThat(r.topicPreferences()).hasSize(1); + assertThat(r.topicPreferences().get(0).topicName()).isEqualTo("weekly"); + assertThat(r.topicPreferences().get(0).subscriptionStatus()).isEqualTo(SubscriptionStatus.OPT_OUT); + // promos not set by the contact -> surfaced via TopicDefaultPreferences (list default OPT_OUT). + assertThat(r.topicDefaultPreferences()).hasSize(1); + assertThat(r.topicDefaultPreferences().get(0).topicName()).isEqualTo("promos"); + assertThat(r.topicDefaultPreferences().get(0).subscriptionStatus()).isEqualTo(SubscriptionStatus.OPT_OUT); + assertThat(r.attributesData()).isEqualTo("{\"name\":\"Alice\"}"); + assertThat(r.unsubscribeAll()).isFalse(); + } + + @Test + @Order(2) + void createContact_duplicate_throwsAlreadyExists() { + assertThatThrownBy(() -> sesV2.createContact(CreateContactRequest.builder() + .contactListName(LIST).emailAddress(EMAIL).build())) + .isInstanceOf(AlreadyExistsException.class) + .hasMessageContaining(EMAIL + " already exists in List."); + } + + @Test + @Order(3) + void getContact_unknown_throwsNotFound() { + assertThatThrownBy(() -> sesV2.getContact(GetContactRequest.builder() + .contactListName(LIST).emailAddress("ghost@example.com").build())) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("ghost@example.com doesn't exist in List."); + } + + @Test + @Order(4) + void createContact_unknownTopic_throwsBadRequest() { + assertThatThrownBy(() -> sesV2.createContact(CreateContactRequest.builder() + .contactListName(LIST).emailAddress("bob@example.com") + .topicPreferences(TopicPreference.builder().topicName("nope") + .subscriptionStatus(SubscriptionStatus.OPT_IN).build()) + .build())) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("doesn't contain Topic: nope"); + } + + @Test + @Order(5) + void listContacts_includesContact() { + assertThat(sesV2.listContacts(r -> r.contactListName(LIST)).contacts()) + .anyMatch(c -> EMAIL.equals(c.emailAddress())); + } + + @Test + @Order(6) + void updateContact_mergesPreferences_replacesAttributes() { + sesV2.updateContact(UpdateContactRequest.builder() + .contactListName(LIST).emailAddress(EMAIL) + .topicPreferences(TopicPreference.builder().topicName("promos") + .subscriptionStatus(SubscriptionStatus.OPT_IN).build()) + .build()); + + GetContactResponse r = sesV2.getContact(GetContactRequest.builder() + .contactListName(LIST).emailAddress(EMAIL).build()); + // TopicPreferences merged (weekly kept + promos added); AttributesData cleared on omit. + assertThat(r.topicPreferences()).hasSize(2); + assertThat(r.attributesData()).isNull(); + } + + @Test + @Order(7) + void deleteContact_removesIt() { + sesV2.deleteContact(DeleteContactRequest.builder() + .contactListName(LIST).emailAddress(EMAIL).build()); + + assertThatThrownBy(() -> sesV2.getContact(GetContactRequest.builder() + .contactListName(LIST).emailAddress(EMAIL).build())) + .isInstanceOf(NotFoundException.class); + } +} diff --git a/docs/services/ses.md b/docs/services/ses.md index b713bc291c..b529c48672 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -212,6 +212,11 @@ Alongside the classic Query API, Floci implements a subset of the SES v2 REST JS | `GET` | `/v2/email/contact-lists/{ContactListName}` | `GetContactList` | | `PUT` | `/v2/email/contact-lists/{ContactListName}` | `UpdateContactList` | | `DELETE` | `/v2/email/contact-lists/{ContactListName}` | `DeleteContactList` | +| `POST` | `/v2/email/contact-lists/{ContactListName}/contacts` | `CreateContact` | +| `POST` | `/v2/email/contact-lists/{ContactListName}/contacts/list` | `ListContacts` | +| `GET` | `/v2/email/contact-lists/{ContactListName}/contacts/{EmailAddress}` | `GetContact` | +| `PUT` | `/v2/email/contact-lists/{ContactListName}/contacts/{EmailAddress}` | `UpdateContact` | +| `DELETE` | `/v2/email/contact-lists/{ContactListName}/contacts/{EmailAddress}` | `DeleteContact` | | `PUT` | `/v2/email/suppression/addresses` | `PutSuppressedDestination` | | `GET` | `/v2/email/suppression/addresses/{EmailAddress}` | `GetSuppressedDestination` | | `DELETE` | `/v2/email/suppression/addresses/{EmailAddress}` | `DeleteSuppressedDestination` | 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 14529eab89..9cd9084009 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 @@ -9,9 +9,11 @@ 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.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; @@ -1342,6 +1344,189 @@ public class SesController { 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)); + } + SesService.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); + SesService.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; + } + // ──────────────────────────── Account ──────────────────────────── @GET @@ -1835,20 +2020,26 @@ public class SesController { if (enabledNode.isMissingNode()) { return false; } - if (enabledNode.isBoolean()) { - return enabledNode.booleanValue(); + return coerceBoolean(enabledNode); + } + + // AWS-verified Jackson coercion for a SES v2 boolean field: a JSON string coerces to true, + // while a number/null/array/object is a SerializationException. + private static boolean coerceBoolean(JsonNode node) { + if (node.isBoolean()) { + return node.booleanValue(); } - if (enabledNode.isTextual()) { + if (node.isTextual()) { return true; } - if (enabledNode.isNull()) { + if (node.isNull()) { throw new AwsException("SerializationException", null, 400); } - if (enabledNode.isNumber()) { + if (node.isNumber()) { throw new AwsException("SerializationException", "NUMBER_VALUE can not be converted to a Boolean", 400); } - throw unexpectedStartError(enabledNode); + throw unexpectedStartError(node); } private static AwsException unexpectedStartError(JsonNode node) { 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 a27531b9dc..9d0132405f 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 @@ -15,6 +15,7 @@ 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.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.DedicatedIpPool; import io.github.hectorvent.floci.services.ses.model.DeliveryOptions; @@ -24,6 +25,7 @@ import io.github.hectorvent.floci.services.ses.model.Identity; 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; @@ -84,8 +86,12 @@ public class SesService { private final StorageBackend accountSuppressionStore; private final StorageBackend dedicatedIpPoolStore; private final StorageBackend contactListStore; + private final StorageBackend contactStore; // Guards the one-list-per-account check-then-create so concurrent creates can't both pass. private final Object contactListCreateLock = new Object(); + // Serializes contact create/update against contact-list deletion so a concurrent delete + // can't purge the list between validation and the write, leaving an orphaned contact. + private final Object contactMutationLock = new Object(); private final SmtpRelay smtpRelay; private final ObjectMapper objectMapper; private final SesEventPublisher eventPublisher; @@ -116,6 +122,8 @@ public class SesService { new TypeReference>() {}); this.contactListStore = storageFactory.create("ses", "ses-contact-lists.json", new TypeReference>() {}); + this.contactStore = storageFactory.create("ses", "ses-contacts.json", + new TypeReference>() {}); this.smtpRelay = smtpRelay; this.objectMapper = objectMapper; this.eventPublisher = eventPublisher; @@ -133,11 +141,13 @@ public class SesService { StorageBackend accountSuppressionStore, StorageBackend dedicatedIpPoolStore, StorageBackend contactListStore, + StorageBackend contactStore, SmtpRelay smtpRelay, ObjectMapper objectMapper, Clock clock) { this(identityStore, emailStore, accountSettingsStore, templateStore, configSetStore, suppressionStore, - accountSuppressionStore, dedicatedIpPoolStore, contactListStore, smtpRelay, objectMapper, null, clock); + accountSuppressionStore, dedicatedIpPoolStore, contactListStore, contactStore, smtpRelay, + objectMapper, null, clock); } SesService(StorageBackend identityStore, @@ -149,6 +159,7 @@ public class SesService { StorageBackend accountSuppressionStore, StorageBackend dedicatedIpPoolStore, StorageBackend contactListStore, + StorageBackend contactStore, SmtpRelay smtpRelay, ObjectMapper objectMapper, Route53Service route53Service, @@ -162,6 +173,7 @@ public class SesService { this.accountSuppressionStore = accountSuppressionStore; this.dedicatedIpPoolStore = dedicatedIpPoolStore; this.contactListStore = contactListStore; + this.contactStore = contactStore; this.smtpRelay = smtpRelay; this.objectMapper = objectMapper; this.eventPublisher = null; @@ -1366,10 +1378,25 @@ public class SesService { public void deleteContactList(String name, String region) { String key = contactListKey(region, name); - if (contactListStore.get(key).isEmpty()) { - throw contactListNotFound(name); + // Existence check, list delete, and contact purge all under the lock: concurrent deletes + // can't both pass the check (one must 404), and a concurrent create/update can't slip a + // contact in after the purge. Contacts are stored independently, so purging them here keeps + // them from leaking into a same-named list recreated later (AWS deletes them with the list). + String prefix = "contact::" + region + "::" + name + "::"; + synchronized (contactMutationLock) { + if (contactListStore.get(key).isEmpty()) { + throw contactListNotFound(name); + } + contactListStore.delete(key); + // Delete by the actual stored keys (not keys rebuilt from each value's EmailAddress), + // so a persisted entry whose key and EmailAddress diverge is still purged. + List contactKeys = contactStore.keys().stream() + .filter(k -> k.startsWith(prefix)) + .toList(); + for (String contactKey : contactKeys) { + contactStore.delete(contactKey); + } } - contactListStore.delete(key); LOG.infov("Deleted SES contact list: {0} in region {1}", name, region); } @@ -1481,6 +1508,196 @@ public class SesService { return "contactList::" + region + "::" + name; } + // ─────────────────────────── Contacts ─────────────────────────── + + private static final Pattern EMAIL_PATTERN = Pattern.compile("^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$"); + + public Contact createContact(String listName, String emailAddress, List topicPreferences, + Boolean unsubscribeAll, String attributesData, String region) { + validateContactInput(listName, emailAddress, topicPreferences, region); + Contact contact = new Contact(emailAddress); + contact.setTopicPreferences(topicPreferences); + contact.setUnsubscribeAll(unsubscribeAll != null && unsubscribeAll); + contact.setAttributesData(attributesData); + Instant now = Instant.now(clock); + contact.setCreatedTimestamp(now); + contact.setLastUpdatedTimestamp(now); + String key = contactKey(region, listName, emailAddress); + // Re-check the list, duplicate, and put under the lock so a concurrent deleteContactList + // can't purge the list between validation and the write (which would orphan this contact). + synchronized (contactMutationLock) { + getContactList(listName, region); + if (contactStore.get(key).isPresent()) { + throw new AwsException("AlreadyExistsException", + emailAddress + " already exists in List.", 400); + } + contactStore.put(key, contact); + } + LOG.infov("Created SES contact {0} in list {1} (region {2})", emailAddress, listName, region); + return contact; + } + + // Read operations return the resolved ContactList alongside the contact(s) so the controller + // can render TopicDefaultPreferences without a second getContactList round-trip (which would + // open a TOCTOU window where a concurrent delete turns a successful read into "List not found"). + public record ContactWithList(Contact contact, ContactList list) { + } + + public record ContactsWithList(List contacts, ContactList list) { + } + + public ContactWithList getContact(String listName, String emailAddress, String region) { + validateEmailAddress(emailAddress); + ContactList list = getContactList(listName, region); + Contact contact = contactStore.get(contactKey(region, listName, emailAddress)) + .orElseThrow(() -> contactNotFound(emailAddress)); + return new ContactWithList(contact, list); + } + + public ContactsWithList listContacts(String listName, String region) { + ContactList list = getContactList(listName, region); + String prefix = "contact::" + region + "::" + listName + "::"; + List contacts = contactStore.scan(k -> k.startsWith(prefix)).stream() + .sorted(Comparator.comparing(Contact::getEmailAddress, + Comparator.nullsFirst(Comparator.naturalOrder()))) + .toList(); + return new ContactsWithList(contacts, list); + } + + public Contact updateContact(String listName, String emailAddress, List topicPreferences, + boolean topicPreferencesPresent, Boolean unsubscribeAll, String attributesData, + String region) { + validateContactInput(listName, emailAddress, topicPreferences, region); + String key = contactKey(region, listName, emailAddress); + Contact existing; + // Re-check the list and read-modify-write under the lock so a concurrent deleteContactList + // can't purge the contact/list between validation and the write (which would resurrect it). + synchronized (contactMutationLock) { + getContactList(listName, region); + existing = contactStore.get(key).orElseThrow(() -> contactNotFound(emailAddress)); + // Verified against real AWS: TopicPreferences merge by topic name (omitting keeps existing); + // AttributesData and UnsubscribeAll are replaced (omitting clears / resets them). + if (topicPreferencesPresent) { + existing.setTopicPreferences(mergeTopicPreferences(existing.getTopicPreferences(), topicPreferences)); + } + existing.setUnsubscribeAll(unsubscribeAll != null && unsubscribeAll); + existing.setAttributesData(attributesData); + existing.setLastUpdatedTimestamp(Instant.now(clock)); + contactStore.put(key, existing); + } + LOG.infov("Updated SES contact {0} in list {1}", emailAddress, listName); + return existing; + } + + public void deleteContact(String listName, String emailAddress, String region) { + validateEmailAddress(emailAddress); + String key = contactKey(region, listName, emailAddress); + // List re-check + existence check + delete under the lock (matching create/update): a + // concurrent deleteContactList then surfaces "list not found" rather than "contact not + // found", and an updateContact can't put a just-deleted contact back (resurrecting it). + synchronized (contactMutationLock) { + getContactList(listName, region); + if (contactStore.get(key).isEmpty()) { + throw contactNotFound(emailAddress); + } + contactStore.delete(key); + } + LOG.infov("Deleted SES contact {0} in list {1}", emailAddress, listName); + } + + /** + * Derives {@code TopicDefaultPreferences}: each list topic the contact has not set an explicit + * preference for, carrying that topic's default subscription status. + */ + public List deriveTopicDefaultPreferences(Contact contact, ContactList list) { + Set explicit = new HashSet<>(); + for (TopicPreference p : contact.getTopicPreferences()) { + explicit.add(p.getTopicName()); + } + List defaults = new ArrayList<>(); + for (Topic t : list.getTopics()) { + if (!explicit.contains(t.getTopicName())) { + defaults.add(new TopicPreference(t.getTopicName(), t.getDefaultSubscriptionStatus())); + } + } + return defaults; + } + + private static AwsException contactNotFound(String emailAddress) { + return new AwsException("NotFoundException", emailAddress + " doesn't exist in List.", 404); + } + + // Validation order verified against real AWS: protocol-layer (Smithy) topic-preference checks + // first, then EmailAddress format, then contact-list existence, then topic existence. + private void validateContactInput(String listName, String emailAddress, List prefs, + String region) { + if (prefs != null) { + for (int i = 0; i < prefs.size(); i++) { + TopicPreference p = prefs.get(i); + String member = "topicPreferences." + (i + 1) + ".member."; + if (p.getTopicName() == null) { + throw validationError(member + "topicName", "Member must not be null"); + } + if (p.getSubscriptionStatus() == null) { + throw validationError(member + "subscriptionStatus", "Member must not be null"); + } + if (!SUBSCRIPTION_STATUSES.contains(p.getSubscriptionStatus())) { + throw validationError(member + "subscriptionStatus", + "Member must satisfy enum value set: [OPT_OUT, OPT_IN]"); + } + } + } + validateEmailAddress(emailAddress); + ContactList list = getContactList(listName, region); + if (prefs != null && !prefs.isEmpty()) { + Set topicNames = new HashSet<>(); + for (Topic t : list.getTopics()) { + topicNames.add(t.getTopicName()); + } + for (TopicPreference p : prefs) { + if (!topicNames.contains(p.getTopicName())) { + throw new AwsException("BadRequestException", + "List: " + listName + " doesn't contain Topic: " + p.getTopicName(), 400); + } + } + } + } + + private static List mergeTopicPreferences(List existing, + List provided) { + Map byTopic = new LinkedHashMap<>(); + if (existing != null) { + for (TopicPreference p : existing) { + byTopic.put(p.getTopicName(), p); + } + } + if (provided != null) { + for (TopicPreference p : provided) { + byTopic.put(p.getTopicName(), p); + } + } + return new ArrayList<>(byTopic.values()); + } + + private static void validateEmailAddress(String emailAddress) { + // Verified against real AWS: a missing/null required member is a Smithy validation error, + // an empty/blank value is "can't be blank", and only a non-blank malformed value is "invalid". + if (emailAddress == null) { + throw validationError("emailAddress", "Member must not be null"); + } + if (emailAddress.isBlank()) { + throw new AwsException("BadRequestException", "EmailAddress can't be blank.", 400); + } + if (!EMAIL_PATTERN.matcher(emailAddress).matches()) { + throw new AwsException("BadRequestException", + "EmailAddress <" + emailAddress + "> is invalid", 400); + } + } + + private static String contactKey(String region, String listName, String emailAddress) { + return "contact::" + region + "::" + listName + "::" + emailAddress; + } + static void validateConfigurationSetName(String name) { if (name == null || name.isBlank()) { throw new AwsException("InvalidParameterValue", diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/Contact.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/Contact.java new file mode 100644 index 0000000000..dd19e374d0 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/Contact.java @@ -0,0 +1,68 @@ +package io.github.hectorvent.floci.services.ses.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +/** + * A contact within an SES V2 contact list: an email address plus its explicit + * per-topic subscription preferences, an unsubscribe-all flag, and free-form + * attributes. {@code TopicDefaultPreferences} is not stored — it is derived at + * read time from the list's topics for topics the contact hasn't set explicitly. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class Contact { + + @JsonProperty("EmailAddress") + private String emailAddress; + + @JsonProperty("TopicPreferences") + private List topicPreferences = new ArrayList<>(); + + @JsonProperty("UnsubscribeAll") + private boolean unsubscribeAll; + + @JsonProperty("AttributesData") + private String attributesData; + + @JsonProperty("CreatedTimestamp") + private Instant createdTimestamp; + + @JsonProperty("LastUpdatedTimestamp") + private Instant lastUpdatedTimestamp; + + public Contact() {} + + public Contact(String emailAddress) { + this.emailAddress = emailAddress; + } + + public String getEmailAddress() { return emailAddress; } + public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } + + public List getTopicPreferences() { return topicPreferences; } + public void setTopicPreferences(List topicPreferences) { + this.topicPreferences = topicPreferences == null ? new ArrayList<>() : topicPreferences; + } + + public boolean isUnsubscribeAll() { return unsubscribeAll; } + public void setUnsubscribeAll(boolean unsubscribeAll) { this.unsubscribeAll = unsubscribeAll; } + + public String getAttributesData() { return attributesData; } + public void setAttributesData(String attributesData) { this.attributesData = attributesData; } + + public Instant getCreatedTimestamp() { return createdTimestamp; } + public void setCreatedTimestamp(Instant createdTimestamp) { this.createdTimestamp = createdTimestamp; } + + public Instant getLastUpdatedTimestamp() { return lastUpdatedTimestamp; } + public void setLastUpdatedTimestamp(Instant lastUpdatedTimestamp) { + this.lastUpdatedTimestamp = lastUpdatedTimestamp; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/TopicPreference.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/TopicPreference.java new file mode 100644 index 0000000000..d66bcbc4c0 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/TopicPreference.java @@ -0,0 +1,37 @@ +package io.github.hectorvent.floci.services.ses.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * A contact's subscription preference for a single SES V2 contact-list topic: + * a topic name and a subscription status ({@code OPT_IN} or {@code OPT_OUT}). + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class TopicPreference { + + @JsonProperty("TopicName") + private String topicName; + + @JsonProperty("SubscriptionStatus") + private String subscriptionStatus; + + public TopicPreference() {} + + public TopicPreference(String topicName, String subscriptionStatus) { + this.topicName = topicName; + this.subscriptionStatus = subscriptionStatus; + } + + public String getTopicName() { return topicName; } + public void setTopicName(String topicName) { this.topicName = topicName; } + + public String getSubscriptionStatus() { return subscriptionStatus; } + public void setSubscriptionStatus(String subscriptionStatus) { + this.subscriptionStatus = subscriptionStatus; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesContactV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesContactV2IntegrationTest.java new file mode 100644 index 0000000000..ba6bab7f9a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesContactV2IntegrationTest.java @@ -0,0 +1,369 @@ +package io.github.hectorvent.floci.services.ses; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.notNullValue; + +/** + * Integration test for SES V2 Contact CRUD under + * {@code /v2/email/contact-lists/{name}/contacts}. Behaviour and error strings + * are verified against real AWS (TopicDefaultPreferences derivation, validation + * order, update merge/replace semantics, and the CRUD error shapes). + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesContactV2IntegrationTest { + + private static final String SES_AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request"; + private static final String LIST = "contacts-it-list"; + private static final String EMAIL = "alice@example.com"; + private static final String CONTACTS = "/v2/email/contact-lists/" + LIST + "/contacts"; + + private static io.restassured.response.Response post(String path, String body) { + return given().contentType("application/json").header("Authorization", SES_AUTH) + .body(body).when().post(path); + } + + @Test + @Order(1) + void setup_createContactList() { + given().contentType("application/json").header("Authorization", SES_AUTH) + .body("{\"ContactListName\":\"" + LIST + "\",\"Topics\":[" + + "{\"TopicName\":\"weekly\",\"DisplayName\":\"Weekly\",\"DefaultSubscriptionStatus\":\"OPT_IN\"}," + + "{\"TopicName\":\"promos\",\"DisplayName\":\"Promos\",\"DefaultSubscriptionStatus\":\"OPT_OUT\"}]}") + .when().post("/v2/email/contact-lists").then().statusCode(200); + } + + @Test + @Order(2) + void createContact() { + post(CONTACTS, "{\"EmailAddress\":\"" + EMAIL + "\",\"TopicPreferences\":[" + + "{\"TopicName\":\"weekly\",\"SubscriptionStatus\":\"OPT_OUT\"}]," + + "\"AttributesData\":\"{\\\"name\\\":\\\"Alice\\\"}\",\"UnsubscribeAll\":false}") + .then().statusCode(200); + } + + @Test + @Order(3) + void getContact_shape() { + given().header("Authorization", SES_AUTH) + .when().get(CONTACTS + "/" + EMAIL) + .then().statusCode(200) + .body("EmailAddress", equalTo(EMAIL)) + .body("TopicPreferences", hasSize(1)) + .body("TopicPreferences[0].TopicName", equalTo("weekly")) + .body("TopicPreferences[0].SubscriptionStatus", equalTo("OPT_OUT")) + // promos not set by the contact -> surfaced via TopicDefaultPreferences (list default). + .body("TopicDefaultPreferences", hasSize(1)) + .body("TopicDefaultPreferences[0].TopicName", equalTo("promos")) + .body("TopicDefaultPreferences[0].SubscriptionStatus", equalTo("OPT_OUT")) + .body("UnsubscribeAll", equalTo(false)) + .body("AttributesData", equalTo("{\"name\":\"Alice\"}")) + .body("CreatedTimestamp", notNullValue()) + .body("LastUpdatedTimestamp", notNullValue()); + } + + @Test + @Order(4) + void createContact_duplicate_returnsAlreadyExists() { + post(CONTACTS, "{\"EmailAddress\":\"" + EMAIL + "\"}") + .then().statusCode(400) + .body("__type", equalTo("AlreadyExistsException")) + .body("message", equalTo(EMAIL + " already exists in List.")); + } + + @Test + @Order(5) + void getContact_unknownEmail_returns404() { + given().header("Authorization", SES_AUTH) + .when().get(CONTACTS + "/ghost@example.com") + .then().statusCode(404) + .body("__type", equalTo("NotFoundException")) + .body("message", equalTo("ghost@example.com doesn't exist in List.")); + } + + @Test + @Order(6) + void getContact_unknownList_returns404() { + given().header("Authorization", SES_AUTH) + .when().get("/v2/email/contact-lists/does-not-exist/contacts/" + EMAIL) + .then().statusCode(404) + .body("message", equalTo("List with name: does-not-exist doesn't exist.")); + } + + @Test + @Order(7) + void createContact_unknownTopic_returns400() { + post(CONTACTS, "{\"EmailAddress\":\"bob@example.com\",\"TopicPreferences\":[" + + "{\"TopicName\":\"nope\",\"SubscriptionStatus\":\"OPT_IN\"}]}") + .then().statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo("List: " + LIST + " doesn't contain Topic: nope")); + } + + @Test + @Order(8) + void createContact_invalidSubscriptionStatus_returns400() { + post(CONTACTS, "{\"EmailAddress\":\"bob@example.com\",\"TopicPreferences\":[" + + "{\"TopicName\":\"weekly\",\"SubscriptionStatus\":\"MAYBE\"}]}") + .then().statusCode(400) + .body("message", equalTo("1 validation error detected: Value at " + + "'topicPreferences.1.member.subscriptionStatus' failed to satisfy constraint: " + + "Member must satisfy enum value set: [OPT_OUT, OPT_IN]")); + } + + @Test + @Order(9) + void createContact_invalidEmail_returns400() { + post(CONTACTS, "{\"EmailAddress\":\"not-an-email\"}") + .then().statusCode(400) + .body("message", equalTo("EmailAddress is invalid")); + } + + @Test + @Order(10) + void createContact_invalidEmailAndInvalidEnum_reportsEnumFirst() { + // Probe-verified: Smithy enum validation precedes the EmailAddress format check. + post(CONTACTS, "{\"EmailAddress\":\"not-an-email\",\"TopicPreferences\":[" + + "{\"TopicName\":\"weekly\",\"SubscriptionStatus\":\"MAYBE\"}]}") + .then().statusCode(400) + .body("message", equalTo("1 validation error detected: Value at " + + "'topicPreferences.1.member.subscriptionStatus' failed to satisfy constraint: " + + "Member must satisfy enum value set: [OPT_OUT, OPT_IN]")); + } + + @Test + @Order(11) + void updateContact_unsubscribeAll_replacesAttributesKeepsPreferences() { + given().contentType("application/json").header("Authorization", SES_AUTH) + .body("{\"UnsubscribeAll\":true}") + .when().put(CONTACTS + "/" + EMAIL).then().statusCode(200); + + given().header("Authorization", SES_AUTH) + .when().get(CONTACTS + "/" + EMAIL) + .then().statusCode(200) + .body("UnsubscribeAll", equalTo(true)) + // TopicPreferences kept; AttributesData cleared (replace semantics). + .body("TopicPreferences", hasSize(1)) + .body("TopicPreferences[0].TopicName", equalTo("weekly")) + .body("AttributesData", org.hamcrest.Matchers.nullValue()); + } + + @Test + @Order(12) + void updateContact_topicPreferences_mergeByTopicName() { + given().contentType("application/json").header("Authorization", SES_AUTH) + .body("{\"TopicPreferences\":[{\"TopicName\":\"promos\",\"SubscriptionStatus\":\"OPT_IN\"}]}") + .when().put(CONTACTS + "/" + EMAIL).then().statusCode(200); + + given().header("Authorization", SES_AUTH) + .when().get(CONTACTS + "/" + EMAIL) + .then().statusCode(200) + // Merged: existing weekly kept + promos added; no topic left for defaults. + .body("TopicPreferences", hasSize(2)) + .body("TopicDefaultPreferences", hasSize(0)); + } + + @Test + @Order(13) + void listContacts_lightweightProjection() { + given().contentType("application/json").header("Authorization", SES_AUTH).body("{}") + .when().post(CONTACTS + "/list") + .then().statusCode(200) + .body("Contacts", hasSize(1)) + .body("Contacts[0].EmailAddress", equalTo(EMAIL)) + .body("Contacts[0].TopicPreferences", hasSize(2)) + .body("Contacts[0].LastUpdatedTimestamp", notNullValue()) + // ListContacts is a lightweight projection: no AttributesData / CreatedTimestamp. + .body("Contacts[0].AttributesData", org.hamcrest.Matchers.nullValue()) + .body("Contacts[0].CreatedTimestamp", org.hamcrest.Matchers.nullValue()); + } + + @Test + @Order(14) + void deleteContact_thenGone() { + given().header("Authorization", SES_AUTH) + .when().delete(CONTACTS + "/" + EMAIL).then().statusCode(200); + + given().header("Authorization", SES_AUTH) + .when().get(CONTACTS + "/" + EMAIL).then().statusCode(404); + } + + @Test + @Order(15) + void deleteContact_unknown_returns404() { + given().header("Authorization", SES_AUTH) + .when().delete(CONTACTS + "/ghost@example.com") + .then().statusCode(404) + .body("message", equalTo("ghost@example.com doesn't exist in List.")); + } + + @Test + @Order(16) + void deleteContactList_purgesContacts_noLeakOnRecreate() { + // Add a contact, delete the list (which must cascade-delete its contacts), then recreate a + // same-named list — the old contact must not leak into it. + post(CONTACTS, "{\"EmailAddress\":\"carol@example.com\"}").then().statusCode(200); + given().header("Authorization", SES_AUTH) + .when().delete("/v2/email/contact-lists/" + LIST).then().statusCode(200); + given().contentType("application/json").header("Authorization", SES_AUTH) + .body("{\"ContactListName\":\"" + LIST + "\",\"Topics\":[" + + "{\"TopicName\":\"weekly\",\"DisplayName\":\"Weekly\"," + + "\"DefaultSubscriptionStatus\":\"OPT_IN\"}]}") + .when().post("/v2/email/contact-lists").then().statusCode(200); + + given().contentType("application/json").header("Authorization", SES_AUTH).body("{}") + .when().post(CONTACTS + "/list") + .then().statusCode(200).body("Contacts", hasSize(0)); + } + + @Test + @Order(17) + void getContact_invalidEmail_returns400() { + // Verified against real AWS: the EmailAddress format is validated before list existence. + given().header("Authorization", SES_AUTH) + .when().get(CONTACTS + "/not-an-email") + .then().statusCode(400) + .body("message", equalTo("EmailAddress is invalid")); + } + + @Test + @Order(18) + void getContact_invalidEmailAndUnknownList_reportsEmailFirst() { + given().header("Authorization", SES_AUTH) + .when().get("/v2/email/contact-lists/does-not-exist/contacts/not-an-email") + .then().statusCode(400) + .body("message", equalTo("EmailAddress is invalid")); + } + + @Test + @Order(19) + void deleteContact_invalidEmail_returns400() { + given().header("Authorization", SES_AUTH) + .when().delete(CONTACTS + "/not-an-email") + .then().statusCode(400) + .body("message", equalTo("EmailAddress is invalid")); + } + + @Test + @Order(20) + void listContacts_nonObjectBody_returns400() { + given().contentType("application/json").header("Authorization", SES_AUTH).body("[]") + .when().post(CONTACTS + "/list") + .then().statusCode(400) + .body("__type", equalTo("BadRequestException")); + } + + // Type coercion — verified against real AWS (Jackson-backed), consistent with parseSendingEnabled: + // a JSON string coerces to the Boolean UnsubscribeAll (any string -> true), but a number is a + // SerializationException; AttributesData (String) rejects non-string types the same way. + + @Test + @Order(21) + void createContact_unsubscribeAllNumber_returns400() { + post(CONTACTS, "{\"EmailAddress\":\"type-a@example.com\",\"UnsubscribeAll\":1}") + .then().statusCode(400) + .body("__type", equalTo("SerializationException")) + .body("message", equalTo("NUMBER_VALUE can not be converted to a Boolean")); + } + + @Test + @Order(22) + void createContact_attributesDataNumber_returns400() { + post(CONTACTS, "{\"EmailAddress\":\"type-b@example.com\",\"AttributesData\":123}") + .then().statusCode(400) + .body("__type", equalTo("SerializationException")) + .body("message", equalTo("NUMBER_VALUE can not be converted to a String")); + } + + @Test + @Order(23) + void createContact_attributesDataBoolean_returns400() { + post(CONTACTS, "{\"EmailAddress\":\"type-c@example.com\",\"AttributesData\":true}") + .then().statusCode(400) + .body("__type", equalTo("SerializationException")) + .body("message", equalTo("TRUE_VALUE can not be converted to a String")); + } + + @Test + @Order(24) + void createContact_unsubscribeAllString_coercesToTrue() { + // AWS coerces ANY JSON string to true for the Boolean field (unlike a number, which is rejected). + post(CONTACTS, "{\"EmailAddress\":\"type-d@example.com\",\"UnsubscribeAll\":\"no\"}") + .then().statusCode(200); + given().header("Authorization", SES_AUTH) + .when().get(CONTACTS + "/type-d@example.com") + .then().statusCode(200).body("UnsubscribeAll", equalTo(true)); + } + + @Test + @Order(25) + void updateContact_attributesDataNumber_returns400() { + given().contentType("application/json").header("Authorization", SES_AUTH) + .body("{\"AttributesData\":123}") + .when().put(CONTACTS + "/" + EMAIL) + .then().statusCode(400) + .body("__type", equalTo("SerializationException")) + .body("message", equalTo("NUMBER_VALUE can not be converted to a String")); + } + + // EmailAddress validation — verified against real AWS: missing/null is a Smithy validation + // error, "" is "can't be blank", and only a non-blank malformed value is "invalid". + + @Test + @Order(26) + void createContact_missingEmail_returnsValidationError() { + post(CONTACTS, "{\"UnsubscribeAll\":false}") + .then().statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo("1 validation error detected: Value at 'emailAddress' " + + "failed to satisfy constraint: Member must not be null")); + } + + @Test + @Order(27) + void createContact_nullEmail_returnsValidationError() { + post(CONTACTS, "{\"EmailAddress\":null}") + .then().statusCode(400) + .body("message", equalTo("1 validation error detected: Value at 'emailAddress' " + + "failed to satisfy constraint: Member must not be null")); + } + + @Test + @Order(28) + void createContact_blankEmail_returnsCantBeBlank() { + post(CONTACTS, "{\"EmailAddress\":\"\"}") + .then().statusCode(400) + .body("message", equalTo("EmailAddress can't be blank.")); + } + + // Runs last: it deletes LIST, so no later ordered test may depend on it. + @Test + @Order(30) + void createOrUpdateContact_intoDeletedList_returns404() { + // Create/update re-check the list under the mutation lock, so a write can't land in a list + // that has been deleted (which would orphan the contact for a same-named list recreated later). + // AWS allows only one contact list per account, so this reuses (and deletes) LIST. + post(CONTACTS, "{\"EmailAddress\":\"bob@example.com\"}").then().statusCode(200); + given().header("Authorization", SES_AUTH) + .when().delete("/v2/email/contact-lists/" + LIST).then().statusCode(200); + + post(CONTACTS, "{\"EmailAddress\":\"ghost@example.com\"}") + .then().statusCode(404) + .body("__type", equalTo("NotFoundException")); + + given().contentType("application/json").header("Authorization", SES_AUTH) + .body("{\"UnsubscribeAll\":true}") + .when().put(CONTACTS + "/bob@example.com") + .then().statusCode(404) + .body("__type", equalTo("NotFoundException")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java index 73ca532eeb..9ce801d65b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java @@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.route53.model.ResourceRecordSet; import io.github.hectorvent.floci.services.ses.model.AccountSuppressionAttributes; import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; import io.github.hectorvent.floci.services.ses.model.ContactList; +import io.github.hectorvent.floci.services.ses.model.Contact; import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool; import io.github.hectorvent.floci.services.ses.model.EmailTemplate; import io.github.hectorvent.floci.services.ses.model.Identity; @@ -55,6 +56,7 @@ class SesServiceDkimLookupCacheTest { new InMemoryStorage(), new InMemoryStorage(), new InMemoryStorage(), + new InMemoryStorage(), mock(SmtpRelay.class), new ObjectMapper(), route53Service, diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java index 5fbb63f3d1..e48a0156dd 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java @@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.ses.model.AccountSuppressionAttributes; import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; import io.github.hectorvent.floci.services.ses.model.ContactList; +import io.github.hectorvent.floci.services.ses.model.Contact; import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool; import io.github.hectorvent.floci.services.ses.model.EmailTemplate; import io.github.hectorvent.floci.services.ses.model.Identity; @@ -44,6 +45,7 @@ class SesServiceLegacyDkimTokensTest { new InMemoryStorage(), new InMemoryStorage(), new InMemoryStorage(), + new InMemoryStorage(), mock(SmtpRelay.class), new ObjectMapper(), Clock.systemUTC()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java index 7be60ddc88..7ab427ad85 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java @@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.ses.model.AccountSuppressionAttributes; import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; import io.github.hectorvent.floci.services.ses.model.ContactList; +import io.github.hectorvent.floci.services.ses.model.Contact; import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool; import io.github.hectorvent.floci.services.ses.model.EmailTemplate; import io.github.hectorvent.floci.services.ses.model.Identity; @@ -43,6 +44,7 @@ class SesServiceSmtpTest { new InMemoryStorage(), new InMemoryStorage(), new InMemoryStorage(), + new InMemoryStorage(), smtpRelay, new ObjectMapper(), Clock.systemUTC()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionLegacyKeyTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionLegacyKeyTest.java index f8b1ed9747..e3f746453c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionLegacyKeyTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionLegacyKeyTest.java @@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.ses.model.AccountSuppressionAttributes; import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; import io.github.hectorvent.floci.services.ses.model.ContactList; +import io.github.hectorvent.floci.services.ses.model.Contact; import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool; import io.github.hectorvent.floci.services.ses.model.EmailTemplate; import io.github.hectorvent.floci.services.ses.model.Identity; @@ -51,6 +52,7 @@ class SesServiceSuppressionLegacyKeyTest { new InMemoryStorage(), new InMemoryStorage(), new InMemoryStorage(), + new InMemoryStorage(), mock(SmtpRelay.class), new ObjectMapper(), Clock.systemUTC()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionReasonTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionReasonTest.java index dc50bb7d54..823002359a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionReasonTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionReasonTest.java @@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.ses.model.AccountSuppressionAttributes; import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; import io.github.hectorvent.floci.services.ses.model.ContactList; +import io.github.hectorvent.floci.services.ses.model.Contact; import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool; import io.github.hectorvent.floci.services.ses.model.EmailTemplate; import io.github.hectorvent.floci.services.ses.model.Identity; @@ -51,6 +52,7 @@ class SesServiceSuppressionReasonTest { accountSuppressionStore, new InMemoryStorage(), new InMemoryStorage(), + new InMemoryStorage(), mock(SmtpRelay.class), new ObjectMapper(), Clock.systemUTC());