Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(ses): apply the ListContacts filter (#4981)

Kenshin Okinakaef9ed507427b
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesContactFilterTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesContactFilterTest.java
new file mode 100644
index 0000000000..b97aeeb3d4
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesContactFilterTest.java
@@ -0,0 +1,84 @@
+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.Test;
+
+import software.amazon.awssdk.services.sesv2.SesV2Client;
+import software.amazon.awssdk.services.sesv2.model.Contact;
+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.ListContactsFilter;
+import software.amazon.awssdk.services.sesv2.model.ListContactsRequest;
+import software.amazon.awssdk.services.sesv2.model.SubscriptionStatus;
+import software.amazon.awssdk.services.sesv2.model.Topic;
+import software.amazon.awssdk.services.sesv2.model.TopicFilter;
+import software.amazon.awssdk.services.sesv2.model.TopicPreference;
+
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
+
+// Runs as its own account, so the one contact list it needs leaves every other test's list alone.
+@DisplayName("SES v2 ListContacts filter")
+class SesContactFilterTest {
+
+ private static final String ACCOUNT_ID = "777788880000";
+ private static final String LIST = "compat-filter-list";
+
+ private static SesV2Client sesV2;
+
+ @BeforeAll
+ static void setup() {
+ assumeFalse(TestFixtures.isRealAws(), "Uses an emulator account picked by the access key");
+ sesV2 = TestFixtures.sesV2Client(ACCOUNT_ID);
+ deleteList();
+ sesV2.createContactList(CreateContactListRequest.builder().contactListName(LIST)
+ .topics(Topic.builder().topicName("news").displayName("News")
+ .defaultSubscriptionStatus(SubscriptionStatus.OPT_IN).build())
+ .build());
+ sesV2.createContact(CreateContactRequest.builder().contactListName(LIST)
+ .emailAddress("[email protected]")
+ .topicPreferences(TopicPreference.builder().topicName("news")
+ .subscriptionStatus(SubscriptionStatus.OPT_OUT).build())
+ .build());
+ sesV2.createContact(CreateContactRequest.builder().contactListName(LIST)
+ .emailAddress("[email protected]").build());
+ }
+
+ @AfterAll
+ static void cleanup() {
+ if (sesV2 != null) {
+ deleteList();
+ sesV2.close();
+ }
+ }
+
+ private static void deleteList() {
+ try {
+ sesV2.deleteContactList(DeleteContactListRequest.builder().contactListName(LIST).build());
+ } catch (Exception ignored) {
+ // Absent on a clean run; a list left by an interrupted run is the only other case.
+ }
+ }
+
+ @Test
+ @DisplayName("Topic filter falls back to the topic default only when asked to")
+ void topicFilterUsesTheDefaultOnlyWhenAsked() {
+ assertThat(optedIn(false)).isEmpty();
+ assertThat(optedIn(true)).containsExactly("[email protected]");
+ }
+
+ private static List<String> optedIn(boolean useDefault) {
+ return sesV2.listContacts(ListContactsRequest.builder().contactListName(LIST)
+ .filter(ListContactsFilter.builder().filteredStatus(SubscriptionStatus.OPT_IN)
+ .topicFilter(TopicFilter.builder().topicName("news")
+ .useDefaultIfPreferenceUnavailable(useDefault).build())
+ .build())
+ .build())
+ .contacts().stream().map(Contact::emailAddress).toList();
+ }
+}
diff --git a/docs/services/ses.md b/docs/services/ses.md
index 5f599fbd4f..ffb0e8b734 100644
--- a/docs/services/ses.md
+++ b/docs/services/ses.md
@@ -448,7 +448,7 @@ The template, identity, configuration-set, custom-verification-template and expo
The tenant lists (`ListTenants`, `ListTenantResources`, `ListResourceTenants`) and `ListImportJobs` page the same way, within 1 to 100. The tenant lists follow real SES (probed 2026-09-25 and 2026-10-02): tenants are listed by name, a tenant's resources by ARN, and a resource's tenants in association order; the tenant or resource is looked up and the filter checked before the page size and token; a page size outside the bound and an empty `NextToken` are reported together in one Smithy validation message; and a token continues only the request it came from, so another tenant, resource or filter refuses it. Floci's own choices, where nothing could be measured: without a `PageSize` the four lists serve up to 100, and `ListImportJobs`, which refuses sandbox accounts and could not be probed at all, is modelled on the tenant lists with jobs listed oldest first.
-The contact lists (`ListContactLists`, `ListContacts`), the dedicated-IP lists (`ListDedicatedIpPools`, `GetDedicatedIps`) and `ListSuppressedDestinations` page the same way, within 1 to 1000. They follow real SES (probed 2026-09-25 and 2026-10-01) in their messages and in the treatment of an empty `NextToken`, refused on the contact and suppressed-destination lists and treated as absent on the dedicated-IP lists. `ListContacts` serves 50 without a `PageSize` and reads the page size and token before it looks the contact list up. A `ListSuppressedDestinations` token continues only the `Reason` filter and tenant it was taken with, and the filter is applied before the page is cut. Floci's own choices: where the SES order is not stable (the pool order changes with the page size, the suppressed-destination order between two identical calls, and contacts follow no recognisable order), Floci lists contacts by address, pools by name and suppressed destinations oldest first; a `ListContacts` page holds exactly `PageSize` contacts, where SES treats the size as a hint and may return a few more or fewer; and without a `PageSize` the contact-list, pool, dedicated-IP and suppressed-destination lists serve up to 1000, since no default could be measured. `ListContacts` does not apply its `Filter` yet: every contact is paged whatever the filter. v1 `ListReceiptRuleSets` has no size member and serves 100 rule sets a page, the figure the AWS model documents; an empty `NextToken` is treated as absent, as on SES. SES lists rule sets by name, while Floci keeps the creation order its unpaged list already had. SES allows 40 rule sets per region, so a second page could not be observed there.
+The contact lists (`ListContactLists`, `ListContacts`), the dedicated-IP lists (`ListDedicatedIpPools`, `GetDedicatedIps`) and `ListSuppressedDestinations` page the same way, within 1 to 1000. They follow real SES (probed 2026-09-25 and 2026-10-01) in their messages and in the treatment of an empty `NextToken`, refused on the contact and suppressed-destination lists and treated as absent on the dedicated-IP lists. `ListContacts` serves 50 without a `PageSize` and reads the page size and token before it looks the contact list up. A `ListSuppressedDestinations` token continues only the `Reason` filter and tenant it was taken with, and the filter is applied before the page is cut. Floci's own choices: where the SES order is not stable (the pool order changes with the page size, the suppressed-destination order between two identical calls, and contacts follow no recognisable order), Floci lists contacts by address, pools by name and suppressed destinations oldest first; a `ListContacts` page holds exactly `PageSize` contacts, where SES treats the size as a hint and may return a few more or fewer; and without a `PageSize` the contact-list, pool, dedicated-IP and suppressed-destination lists serve up to 1000, since no default could be measured. `ListContacts` applies its `Filter` before the page is cut, so a filtered page is exact too, where SES cuts the page first and may return it short or empty; as on SES, a token is not tied to the filter it was taken with. v1 `ListReceiptRuleSets` has no size member and serves 100 rule sets a page, the figure the AWS model documents; an empty `NextToken` is treated as absent, as on SES. SES lists rule sets by name, while Floci keeps the creation order its unpaged list already had. SES allows 40 rule sets per region, so a second page could not be observed there.
DKIM follows AWS's domain-centric model. A **domain** identity carries DKIM tokens (generated at verification, stable across `VerifyDomainDkim` calls); its `DkimVerificationStatus` tracks **DNS record detection** — it transitions to `Success` when the expected `<token>._domainkey.<domain>` CNAMEs are present in the Route53 emulation, not when DKIM is enabled. An **email** identity has no DKIM of its own: its `DkimAttributes` (`SigningEnabled`, `Status`, `Tokens`) are inherited from its parent domain identity when one is registered. The parent is the exact domain after the `@` (verified against AWS): a verified `example.com` covers `[email protected]` but not `[email protected]` unless `mail.example.com` is itself a registered identity. `SetIdentityDkimEnabled` / `PutEmailIdentityDkimAttributes` only toggle the signing flag (they no longer force the verification status); `PutEmailIdentityDkimSigningAttributes` sets the signing origin (`AWS_SES` Easy DKIM — regenerating tokens when the key length changes — or `EXTERNAL` BYODKIM).
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
index 247f736910..380d64ae27 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesContactController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesContactController.java
@@ -34,12 +34,15 @@ 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.coerceBooleanOrFalse;
import static io.github.hectorvent.floci.services.ses.SesV2Json.intMemberOrAbsent;
import static io.github.hectorvent.floci.services.ses.SesV2Json.parseTagsArray;
import static io.github.hectorvent.floci.services.ses.SesV2Json.putTimestamp;
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.stringMemberOrAbsent;
+import static io.github.hectorvent.floci.services.ses.SesV2Json.structureMemberOrAbsent;
+import static io.github.hectorvent.floci.services.ses.SesV2Json.typedStringMemberOrAbsent;
import static io.github.hectorvent.floci.services.ses.SesV2Json.unexpectedStartError;
/**
@@ -237,9 +240,6 @@ public class SesContactController {
@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 pages
- // the contacts (filtering not yet implemented) and rejects a malformed or non-object body
- // like the other v2 endpoints.
String region = regionResolver.resolveRegion(headers);
try {
JsonNode request = (body == null || body.isBlank())
@@ -249,7 +249,7 @@ public class SesContactController {
Integer pageSize = intMemberOrAbsent(request, "PageSize");
String nextToken = stringMemberOrAbsent(request, "NextToken");
SesContactService.ContactPage listed = contactService.listContacts(contactListName, region,
- SesListPaging.V2_LIST_CONTACTS, pageSize, nextToken);
+ SesListPaging.V2_LIST_CONTACTS, pageSize, nextToken, parseContactFilter(request));
ObjectNode result = objectMapper.createObjectNode();
ArrayNode arr = result.putArray("Contacts");
for (Contact c : listed.contacts().items()) {
@@ -264,6 +264,21 @@ public class SesContactController {
}
}
+ private static SesContactService.ContactFilter parseContactFilter(JsonNode request) {
+ JsonNode filterNode = structureMemberOrAbsent(request, "Filter");
+ if (filterNode.isMissingNode() || filterNode.isNull()) {
+ return null;
+ }
+ JsonNode topicNode = structureMemberOrAbsent(filterNode, "TopicFilter");
+ SesContactService.TopicFilter topicFilter = null;
+ if (!topicNode.isMissingNode() && !topicNode.isNull()) {
+ topicFilter = new SesContactService.TopicFilter(typedStringMemberOrAbsent(topicNode, "TopicName"),
+ coerceBooleanOrFalse(topicNode.path("UseDefaultIfPreferenceUnavailable")));
+ }
+ return new SesContactService.ContactFilter(typedStringMemberOrAbsent(filterNode, "FilteredStatus"),
+ topicFilter);
+ }
+
@GET
@Path("/contact-lists/{contactListName}/contacts/{emailAddress}")
public Response getContact(@Context HttpHeaders headers,
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesContactService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesContactService.java
index 285d7445a0..ebbb9607a8 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesContactService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesContactService.java
@@ -361,19 +361,76 @@ public class SesContactService {
public record ContactPage(PaginatedResult<Contact> contacts, ContactList list) {
}
- /** SES reads the page size and the token before it looks the list up. */
+ /** A ListContacts {@code Filter}; {@code topicFilter} is null when the request has none. */
+ public record ContactFilter(String filteredStatus, TopicFilter topicFilter) {
+ }
+
+ public record TopicFilter(String topicName, boolean useDefaultIfPreferenceUnavailable) {
+ }
+
+ /**
+ * SES checks the status enum, then the page size, then the filter's shape, then the token, the
+ * list and last the topic. SES cuts the page before it filters, so its filtered pages come back
+ * short or empty; Floci filters first and returns exact pages. The token is a position in the
+ * list, not bound to the filter, so SES and Floci both take one across filters.
+ */
public ContactPage listContacts(String listName, String region, SesListPaging paging, Integer pageSize,
- String nextToken) {
+ String nextToken, ContactFilter filter) {
+ if (filter != null && filter.filteredStatus() != null
+ && !SUBSCRIPTION_STATUSES.contains(filter.filteredStatus())) {
+ throw validationError("filter.filteredStatus",
+ "Member must satisfy enum value set: [OPT_OUT, OPT_IN]");
+ }
+ // Validated here as well as in page() so the size error wins over the filter's shape.
+ paging.pageSize(pageSize);
+ if (filter != null) {
+ if (filter.filteredStatus() == null) {
+ throw new AwsException("BadRequestException", "Invalid FilteredStatus <null>", 400);
+ }
+ if (filter.topicFilter() != null && (filter.topicFilter().topicName() == null
+ || filter.topicFilter().topicName().isBlank())) {
+ throw new AwsException("BadRequestException", "TopicName can't be blank in TopicFilter.", 400);
+ }
+ }
ContactList list = contactListStore.get(contactListKey(region, listName)).orElse(null);
- List<Contact> contacts = list == null ? List.of() : contactsOf(listName, region);
+ String topicName = filter == null || filter.topicFilter() == null ? null : filter.topicFilter().topicName();
+ boolean topicFound = topicName == null || (list != null && defaultTopicStatus(list, topicName) != null);
+ List<Contact> contacts = list == null || !topicFound ? List.of()
+ : contactsOf(listName, region).stream().filter(c -> matchesFilter(c, list, filter)).toList();
PaginatedResult<Contact> page = paging.page(region, contacts, Contact::getEmailAddress, pageSize,
nextToken);
if (list == null) {
throw contactListNotFound(listName);
}
+ if (!topicFound) {
+ throw new AwsException("NotFoundException",
+ "List: " + listName + " doesn't contain Topic: " + topicName, 404);
+ }
return new ContactPage(page, list);
}
+ // UnsubscribeAll is OPT_OUT for every topic. Without a topic it is the only thing a status
+ // matches; with one, an explicit preference decides, and the topic default only when asked for.
+ private boolean matchesFilter(Contact contact, ContactList list, ContactFilter filter) {
+ if (filter == null) {
+ return true;
+ }
+ TopicFilter topicFilter = filter.topicFilter();
+ String status;
+ if (contact.isUnsubscribeAll()) {
+ status = "OPT_OUT";
+ } else if (topicFilter == null) {
+ status = "OPT_IN";
+ } else if (explicitTopicStatus(contact, topicFilter.topicName()) != null) {
+ status = explicitTopicStatus(contact, topicFilter.topicName());
+ } else if (topicFilter.useDefaultIfPreferenceUnavailable()) {
+ status = defaultTopicStatus(list, topicFilter.topicName());
+ } else {
+ return false;
+ }
+ return filter.filteredStatus().equals(status);
+ }
+
public ContactsWithList listContacts(String listName, String region) {
ContactList list = getContactList(listName, region);
return new ContactsWithList(contactsOf(listName, region), list);
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesV2Json.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesV2Json.java
index 471a32610e..46dea7413f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesV2Json.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesV2Json.java
@@ -145,6 +145,42 @@ final class SesV2Json {
throw unexpectedStartError(node);
}
+ /**
+ * A structure member as the AWS deserializer reads it: absent or null is returned as is, an
+ * array is "Start of list found where not expected" and any other non-object "Expected null".
+ */
+ static JsonNode structureMemberOrAbsent(JsonNode parent, String field) {
+ JsonNode node = parent.path(field);
+ if (node.isMissingNode() || node.isNull() || node.isObject()) {
+ return node;
+ }
+ if (node.isArray()) {
+ throw unexpectedStartError(node);
+ }
+ throw new AwsException("SerializationException", "Expected null", 400);
+ }
+
+ /** A string member with the AWS deserializer's message for each wrong JSON type. */
+ static String typedStringMemberOrAbsent(JsonNode parent, String field) {
+ JsonNode node = parent.path(field);
+ if (node.isMissingNode() || 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);
+ }
+
static AwsException unexpectedStartError(JsonNode node) {
if (node.isArray()) {
return new AwsException("SerializationException",
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesContactFilterServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesContactFilterServiceTest.java
new file mode 100644
index 0000000000..eb2bc03c29
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesContactFilterServiceTest.java
@@ -0,0 +1,161 @@
+package io.github.hectorvent.floci.services.ses;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.PaginatedResult;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import io.github.hectorvent.floci.services.ses.SesContactService.ContactFilter;
+import io.github.hectorvent.floci.services.ses.SesContactService.TopicFilter;
+import io.github.hectorvent.floci.services.ses.model.Contact;
+import io.github.hectorvent.floci.services.ses.model.Topic;
+import io.github.hectorvent.floci.services.ses.model.TopicPreference;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.function.Executable;
+
+import java.time.Clock;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * The ListContacts {@code Filter}. The fixture is the one the filter was probed with on real SES v2:
+ * topic {@code tin} defaults to OPT_IN and {@code tout} to OPT_OUT, and every expected list below is
+ * what SES returned for the same contacts and filter.
+ */
+class SesContactFilterServiceTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String LIST = "filter-list";
+ private static final String IN = "OPT_IN";
+ private static final String OUT = "OPT_OUT";
+
+ private SesContactService service;
+
+ @BeforeEach
+ void setUp() {
+ service = new SesContactService(new InMemoryStorage<>(), new InMemoryStorage<>(), Clock.systemUTC());
+ service.createContactList(LIST, "d", List.of(new Topic("tin", "In", IN, "d"),
+ new Topic("tout", "Out", OUT, "d")), List.of(), REGION);
+ contact("c1", false, new TopicPreference("tin", OUT), new TopicPreference("tout", IN));
+ contact("c2", false, new TopicPreference("tin", IN), new TopicPreference("tout", OUT));
+ contact("c3", false);
+ contact("c4", true);
+ contact("c5", true, new TopicPreference("tin", IN), new TopicPreference("tout", IN));
+ contact("c6", false, new TopicPreference("tin", OUT));
+ contact("c7", false, new TopicPreference("tout", IN));
+ }
+
+ @Test
+ void filteredStatusAlone_matchesUnsubscribeAllOnly() {
+ assertEquals(List.of("c1", "c2", "c3", "c6", "c7"), names(new ContactFilter(IN, null)));
+ assertEquals(List.of("c4", "c5"), names(new ContactFilter(OUT, null)));
+ }
+
+ @Test
+ void topicFilter_usesTheTopicDefaultOnlyWhenAskedTo() {
+ assertEquals(List.of("c2"), names(topic(IN, "tin", false)));
+ assertEquals(List.of("c2", "c3", "c7"), names(topic(IN, "tin", true)));
+ assertEquals(List.of("c1", "c4", "c5", "c6"), names(topic(OUT, "tin", false)));
+ assertEquals(List.of("c1", "c4", "c5", "c6"), names(topic(OUT, "tin", true)));
+ assertEquals(List.of("c1", "c7"), names(topic(IN, "tout", false)));
+ assertEquals(List.of("c1", "c7"), names(topic(IN, "tout", true)));
+ assertEquals(List.of("c2", "c4", "c5"), names(topic(OUT, "tout", false)));
+ assertEquals(List.of("c2", "c3", "c4", "c5", "c6"), names(topic(OUT, "tout", true)));
+ }
+
+ @Test
+ void filteredPages_areExactAndTheTokenIsNotBoundToTheFilter() {
+ PaginatedResult<Contact> first = page(new ContactFilter(IN, null), 2, null);
+ assertEquals(List.of("c1", "c2"), names(first.items()));
+ PaginatedResult<Contact> second = page(new ContactFilter(IN, null), 2, first.nextToken());
+ assertEquals(List.of("c3", "c6"), names(second.items()));
+ // The token is a position, so another filter (or none) continues from the same place.
+ assertEquals(List.of("c3", "c4"), names(page(null, 2, first.nextToken()).items()));
+ assertEquals(List.of("c4", "c5"), names(page(new ContactFilter(OUT, null), 2, first.nextToken()).items()));
+ }
+
+ @Test
+ void lastFilteredPage_hasNoToken() {
+ PaginatedResult<Contact> only = page(new ContactFilter(OUT, null), 2, null);
+ assertEquals(List.of("c4", "c5"), names(only.items()));
+ assertNull(only.nextToken());
+ }
+
+ @Test
+ void invalidStatus_isAValidationError() {
+ assertError("BadRequestException", "1 validation error detected: Value at 'filter.filteredStatus' "
+ + "failed to satisfy constraint: Member must satisfy enum value set: [OPT_OUT, OPT_IN]",
+ () -> service.listContacts(LIST, REGION, SesListPaging.V2_LIST_CONTACTS, null, null,
+ new ContactFilter("opt_in", null)));
+ }
+
+ @Test
+ void missingStatusOrBlankTopic_isRejected() {
+ assertError("BadRequestException", "Invalid FilteredStatus <null>",
+ () -> list(LIST, null, null, new ContactFilter(null, new TopicFilter("tin", false))));
+ assertError("BadRequestException", "TopicName can't be blank in TopicFilter.",
+ () -> list(LIST, null, null, topic(IN, "", false)));
+ assertError("BadRequestException", "TopicName can't be blank in TopicFilter.",
+ () -> list(LIST, null, null, topic(IN, null, false)));
+ }
+
+ @Test
+ void unknownTopic_isNotFoundAfterTheList() {
+ assertError("NotFoundException", "List: filter-list doesn't contain Topic: nope",
+ () -> list(LIST, null, null, topic(IN, "nope", true)));
+ assertError("NotFoundException", "List with name: ghost doesn't exist.",
+ () -> list("ghost", null, null, topic(IN, "nope", false)));
+ }
+
+ // Probed precedence: enum, page size, filter shape, token, list, topic.
+ @Test
+ void errors_followTheProbedPrecedence() {
+ assertError("BadRequestException", "1 validation error detected: Value at 'filter.filteredStatus' "
+ + "failed to satisfy constraint: Member must satisfy enum value set: [OPT_OUT, OPT_IN]",
+ () -> list("ghost", 0, "garbage", new ContactFilter("BOGUS", new TopicFilter("", false))));
+ assertError("BadRequestException", "The page size must be between 1 and 1000",
+ () -> list(LIST, 0, null, new ContactFilter(null, null)));
+ assertError("BadRequestException", "TopicName can't be blank in TopicFilter.",
+ () -> list("ghost", null, "garbage", topic(IN, "", false)));
+ assertError("BadRequestException", "Provided NextToken is invalid",
+ () -> list(LIST, null, "garbage", topic(IN, "nope", false)));
+ }
+
+ private void contact(String name, boolean unsubscribeAll, TopicPreference... preferences) {
+ service.createContact(LIST, name + "@example.com", List.of(preferences), unsubscribeAll, null, REGION);
+ }
+
+ private static ContactFilter topic(String status, String topicName, boolean useDefault) {
+ return new ContactFilter(status, new TopicFilter(topicName, useDefault));
+ }
+
+ private List<String> names(ContactFilter filter) {
+ return names(page(filter, 1000, null).items());
+ }
+
+ private PaginatedResult<Contact> page(ContactFilter filter, Integer pageSize, String token) {
+ return list(LIST, pageSize, token, filter).contacts();
+ }
+
+ private SesContactService.ContactPage list(String listName, Integer pageSize, String token,
+ ContactFilter filter) {
+ return service.listContacts(listName, REGION, SesListPaging.V2_LIST_CONTACTS, pageSize, token, filter);
+ }
+
+ private static List<String> names(List<Contact> contacts) {
+ List<String> names = new ArrayList<>();
+ for (Contact contact : contacts) {
+ names.add(contact.getEmailAddress().substring(0, contact.getEmailAddress().indexOf('@')));
+ }
+ return names;
+ }
+
+ private static void assertError(String code, String message, Executable call) {
+ AwsException e = assertThrows(AwsException.class, call);
+ assertEquals(code, e.getErrorCode());
+ assertEquals(message, e.getMessage());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesContactFilterV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesContactFilterV2IntegrationTest.java
new file mode 100644
index 0000000000..9f15fe8e93
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesContactFilterV2IntegrationTest.java
@@ -0,0 +1,152 @@
+package io.github.hectorvent.floci.services.ses;
+
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.ValidatableResponse;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.nullValue;
+
+/**
+ * ListContacts {@code Filter} on the wire: parsing, the SES v2 boolean coercion of
+ * UseDefaultIfPreferenceUnavailable, exact filtered pages and the error statuses. The membership
+ * rules and the full error precedence are covered by {@code SesContactFilterServiceTest}.
+ */
+@QuarkusTest
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
+class SesContactFilterV2IntegrationTest {
+
+ private static final String REGION = "me-central-1";
+ private static final String AUTH =
+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/" + REGION + "/ses/aws4_request";
+ private static final String LIST = "filter-wire";
+ private static final String CONTACTS = "/v2/email/contact-lists/" + LIST + "/contacts";
+
+ private boolean created;
+
+ // Not @BeforeAll: the Quarkus test port is only bound once the first test starts.
+ @BeforeEach
+ void createContacts() {
+ if (created) {
+ return;
+ }
+ send("/v2/email/contact-lists", """
+ {"ContactListName": "%s", "Topics": [
+ {"TopicName": "news", "DisplayName": "News", "DefaultSubscriptionStatus": "OPT_IN"}]}
+ """.formatted(LIST)).statusCode(200);
+ // a and c opted out of news explicitly, b and d have no preference, e unsubscribed from all.
+ contact("a", "{\"TopicName\":\"news\",\"SubscriptionStatus\":\"OPT_OUT\"}", false);
+ contact("b", "", false);
+ contact("c", "{\"TopicName\":\"news\",\"SubscriptionStatus\":\"OPT_OUT\"}", false);
+ contact("d", "", false);
+ contact("e", "", true);
+ created = true;
+ }
+
+ @Test
+ void topicFilter_withDefault_pagesTheFilteredSetExactly() {
+ String filter = "\"Filter\": {\"FilteredStatus\": \"OPT_IN\", \"TopicFilter\": "
+ + "{\"TopicName\": \"news\", \"UseDefaultIfPreferenceUnavailable\": \"yes\"}}";
+ String token = list("{" + filter + ", \"PageSize\": 1}")
+ .body("Contacts.EmailAddress", contains("[email protected]"))
+ .extract().path("NextToken");
+ list("{" + filter + ", \"PageSize\": 1, \"NextToken\": \"" + token + "\"}")
+ .body("Contacts.EmailAddress", contains("[email protected]"))
+ .body("NextToken", nullValue());
+ }
+
+ @Test
+ void topicFilter_withoutDefault_skipsContactsWithoutAPreference() {
+ list("{\"Filter\": {\"FilteredStatus\": \"OPT_OUT\", \"TopicFilter\": {\"TopicName\": \"news\"}}}")
+ .body("Contacts.EmailAddress", contains("[email protected]", "[email protected]", "[email protected]"));
+ }
+
+ @Test
+ void filteredStatusAlone_selectsUnsubscribeAll() {
+ list("{\"Filter\": {\"FilteredStatus\": \"OPT_OUT\"}}")
+ .body("Contacts.EmailAddress", contains("[email protected]"));
+ }
+
+ @Test
+ void useDefault_rejectsAStringThatIsNotABoolean() {
+ send(CONTACTS + "/list", "{\"Filter\": {\"FilteredStatus\": \"OPT_IN\", \"TopicFilter\": "
+ + "{\"TopicName\": \"news\", \"UseDefaultIfPreferenceUnavailable\": \"abc\"}}}")
+ .statusCode(400)
+ .body("__type", equalTo("SerializationException"))
+ .body("message", equalTo("STRING_VALUE can not be converted to an Boolean"));
+ }
+
+ @Test
+ void errors_carryTheProbedStatusesAndMessages() {
+ send(CONTACTS + "/list", "{\"Filter\": {}}").statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo("Invalid FilteredStatus <null>"));
+ send(CONTACTS + "/list", "{\"Filter\": {\"FilteredStatus\": \"OPT_IN\", \"TopicFilter\": {}}}")
+ .statusCode(400)
+ .body("message", equalTo("TopicName can't be blank in TopicFilter."));
+ send(CONTACTS + "/list", "{\"Filter\": {\"FilteredStatus\": \"OPT_IN\", \"TopicFilter\": "
+ + "{\"TopicName\": \"nope\"}}}")
+ .statusCode(404)
+ .body("__type", equalTo("NotFoundException"))
+ .body("message", equalTo("List: " + LIST + " doesn't contain Topic: nope"));
+ }
+
+ @Test
+ void wrongJsonTypes_areSerializationExceptions() {
+ send(CONTACTS + "/list", "{\"Filter\": []}").statusCode(400)
+ .body("__type", equalTo("SerializationException"))
+ .body("message", equalTo("Start of list found where not expected"));
+ send(CONTACTS + "/list", "{\"Filter\": {\"FilteredStatus\": \"OPT_IN\", \"TopicFilter\": \"x\"}}")
+ .statusCode(400)
+ .body("__type", equalTo("SerializationException"))
+ .body("message", equalTo("Expected null"));
+ send(CONTACTS + "/list", "{\"Filter\": {\"FilteredStatus\": 1}, \"PageSize\": 0}").statusCode(400)
+ .body("__type", equalTo("SerializationException"))
+ .body("message", equalTo("NUMBER_VALUE can not be converted to a String"));
+ }
+
+ @Test
+ void topicName_isMatchedExactly() {
+ send(CONTACTS + "/list", "{\"Filter\": {\"FilteredStatus\": \"OPT_IN\", \"TopicFilter\": "
+ + "{\"TopicName\": \" news \"}}}")
+ .statusCode(404)
+ .body("message", equalTo("List: " + LIST + " doesn't contain Topic: news "));
+ send(CONTACTS + "/list", "{\"Filter\": {\"FilteredStatus\": \"OPT_IN\", \"TopicFilter\": "
+ + "{\"TopicName\": \" \"}}}")
+ .statusCode(400)
+ .body("message", equalTo("TopicName can't be blank in TopicFilter."));
+ }
+
+ @Test
+ void nullTopicFilter_isTreatedAsAbsent() {
+ list("{\"Filter\": {\"FilteredStatus\": \"OPT_OUT\", \"TopicFilter\": null}}")
+ .body("Contacts.EmailAddress", contains("[email protected]"));
+ }
+
+ @Test
+ void filterOnAMissingList_reportsTheListBeforeTheTopic() {
+ send("/v2/email/contact-lists/ghost/contacts/list", "{\"Filter\": {\"FilteredStatus\": \"OPT_IN\", "
+ + "\"TopicFilter\": {\"TopicName\": \"nope\"}}}")
+ .statusCode(404)
+ .body("message", equalTo("List with name: ghost doesn't exist."));
+ }
+
+ private void contact(String name, String preference, boolean unsubscribeAll) {
+ send(CONTACTS, """
+ {"EmailAddress": "%[email protected]", "TopicPreferences": [%s], "UnsubscribeAll": %s}
+ """.formatted(name, preference, unsubscribeAll)).statusCode(200);
+ }
+
+ private static ValidatableResponse list(String body) {
+ return send(CONTACTS + "/list", body).statusCode(200);
+ }
+
+ private static ValidatableResponse send(String path, String body) {
+ return given().contentType("application/json").header("Authorization", AUTH).body(body)
+ .when().post(path).then();
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesV2JsonTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2JsonTest.java
index 4531f39960..2049c002e4 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesV2JsonTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2JsonTest.java
@@ -164,6 +164,38 @@ class SesV2JsonTest {
}
}
+ @Test
+ void structureMemberOrAbsent_rejectsANonObjectTheWayAwsDoes() {
+ JsonNode node = json("{\"o\":{},\"n\":null,\"a\":[],\"s\":\"x\",\"i\":1}");
+ assertTrue(SesV2Json.structureMemberOrAbsent(node, "o").isObject());
+ assertTrue(SesV2Json.structureMemberOrAbsent(node, "n").isNull());
+ assertTrue(SesV2Json.structureMemberOrAbsent(node, "missing").isMissingNode());
+ assertEquals("Start of list found where not expected", assertAws("SerializationException", 400,
+ () -> SesV2Json.structureMemberOrAbsent(node, "a")).getMessage());
+ assertEquals("Expected null", assertAws("SerializationException", 400,
+ () -> SesV2Json.structureMemberOrAbsent(node, "s")).getMessage());
+ assertEquals("Expected null", assertAws("SerializationException", 400,
+ () -> SesV2Json.structureMemberOrAbsent(node, "i")).getMessage());
+ }
+
+ @Test
+ void typedStringMemberOrAbsent_namesTheWrongType() {
+ JsonNode node = json("{\"s\":\"x\",\"n\":null,\"i\":1,\"t\":true,\"f\":false,\"o\":{},\"a\":[]}");
+ assertEquals("x", SesV2Json.typedStringMemberOrAbsent(node, "s"));
+ assertNull(SesV2Json.typedStringMemberOrAbsent(node, "n"));
+ assertNull(SesV2Json.typedStringMemberOrAbsent(node, "missing"));
+ assertEquals("NUMBER_VALUE can not be converted to a String", assertAws("SerializationException", 400,
+ () -> SesV2Json.typedStringMemberOrAbsent(node, "i")).getMessage());
+ assertEquals("TRUE_VALUE can not be converted to a String", assertAws("SerializationException", 400,
+ () -> SesV2Json.typedStringMemberOrAbsent(node, "t")).getMessage());
+ assertEquals("FALSE_VALUE can not be converted to a String", assertAws("SerializationException", 400,
+ () -> SesV2Json.typedStringMemberOrAbsent(node, "f")).getMessage());
+ assertEquals("Start of structure or map found where not expected.", assertAws("SerializationException",
+ 400, () -> SesV2Json.typedStringMemberOrAbsent(node, "o")).getMessage());
+ assertEquals("Start of list found where not expected", assertAws("SerializationException", 400,
+ () -> SesV2Json.typedStringMemberOrAbsent(node, "a")).getMessage());
+ }
+
@Test
void unexpectedStartError_distinguishesListFromStructure() {
assertEquals("Start of list found where not expected",