Light, fluffy, and always free - The AWS Local Emulator alternative
feat(ses): paginate the contact, dedicated IP pool, suppressed destination and receipt rule set lists (#4877)
Kenshin Okinakabb3dd2de9247
diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.javaindex 79fb8e0a7d..ea94fb6f94 100644--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java@@ -969,6 +969,19 @@ public final class TestFixtures {.build();}+ /**+ * An SES v2 client acting as {@code accountId}, which the emulator reads from a 12-digit access+ * key: SES allows one contact list per account, so a test that needs its own list uses an+ * account no other test touches.+ */+ public static SesV2Client sesV2Client(String accountId) {+ return SesV2Client.builder()+ .endpointOverride(ENDPOINT)+ .region(REGION)+ .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accountId, "test")))+ .build();+ }+public static Route53Client route53Client() {return route53Client("test");}diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesContactPagingTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesContactPagingTest.javanew file mode 100644index 0000000000..23f3bc2bb9--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesContactPagingTest.java@@ -0,0 +1,82 @@+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.ListContactListsRequest;+import software.amazon.awssdk.services.sesv2.model.ListContactsRequest;+import software.amazon.awssdk.services.sesv2.model.ListContactsResponse;++import java.util.ArrayList;+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 contact and contact list paging")+class SesContactPagingTest {++ private static final String ACCOUNT_ID = "777788889999";+ private static final String LIST = "compat-paging-list";+ private static final List<String> ADDRESSES =++ 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).build());+ for (String address : ADDRESSES) {+ sesV2.createContact(CreateContactRequest.builder()+ .contactListName(LIST).emailAddress(address).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("Paginator walks one-item pages over every contact once")+ void paginatorWalksEveryContactOnce() {+ List<String> listed = new ArrayList<>();+ for (ListContactsResponse page : sesV2.listContactsPaginator(+ ListContactsRequest.builder().contactListName(LIST).pageSize(1).build())) {+ assertThat(page.contacts()).hasSizeLessThanOrEqualTo(1);+ page.contacts().stream().map(Contact::emailAddress).forEach(listed::add);+ }++ assertThat(listed).containsExactlyInAnyOrderElementsOf(ADDRESSES);+ }++ @Test+ @DisplayName("Contact list paginator returns the one list")+ void contactListPaginatorReturnsTheList() {+ assertThat(sesV2.listContactListsPaginator(ListContactListsRequest.builder().pageSize(1).build())+ .stream().flatMap(page -> page.contactLists().stream()).map(cl -> cl.contactListName()))+ .containsExactly(LIST);+ }+}diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesDedicatedIpPoolPagingTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesDedicatedIpPoolPagingTest.javanew file mode 100644index 0000000000..abaee52445--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesDedicatedIpPoolPagingTest.java@@ -0,0 +1,70 @@+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.CreateDedicatedIpPoolRequest;+import software.amazon.awssdk.services.sesv2.model.DeleteDedicatedIpPoolRequest;+import software.amazon.awssdk.services.sesv2.model.GetDedicatedIpsRequest;+import software.amazon.awssdk.services.sesv2.model.ListDedicatedIpPoolsRequest;+import software.amazon.awssdk.services.sesv2.model.ListDedicatedIpPoolsResponse;++import java.util.ArrayList;+import java.util.List;++import static org.assertj.core.api.Assertions.assertThat;++@DisplayName("SES v2 dedicated IP pool list paging")+class SesDedicatedIpPoolPagingTest {++ private static SesV2Client sesV2;+ private static List<String> names;++ @BeforeAll+ static void setup() {+ sesV2 = TestFixtures.sesV2Client();+ String prefix = "sdk-page-" + TestFixtures.uniqueName() + "-";+ names = List.of(prefix + "b", prefix + "c", prefix + "a");+ for (String name : names) {+ sesV2.createDedicatedIpPool(CreateDedicatedIpPoolRequest.builder().poolName(name).build());+ }+ }++ @AfterAll+ static void cleanup() {+ if (sesV2 != null) {+ for (String name : names) {+ try {+ sesV2.deleteDedicatedIpPool(DeleteDedicatedIpPoolRequest.builder().poolName(name).build());+ } catch (Exception ignored) {+ // Best-effort cleanup; a leftover pool does not affect other tests.+ }+ }+ sesV2.close();+ }+ }++ @Test+ @DisplayName("Paginator walks one-item pages over every pool once")+ void paginatorWalksEveryPoolOnce() {+ List<String> listed = new ArrayList<>();+ for (ListDedicatedIpPoolsResponse page : sesV2.listDedicatedIpPoolsPaginator(+ ListDedicatedIpPoolsRequest.builder().pageSize(1).build())) {+ assertThat(page.dedicatedIpPools()).hasSizeLessThanOrEqualTo(1);+ listed.addAll(page.dedicatedIpPools());+ }++ assertThat(listed).doesNotHaveDuplicates();+ assertThat(listed.stream().filter(names::contains)).containsExactlyInAnyOrderElementsOf(names);+ }++ @Test+ @DisplayName("GetDedicatedIps paginator ends on an empty page")+ void getDedicatedIpsPaginatorEnds() {+ assertThat(sesV2.getDedicatedIpsPaginator(GetDedicatedIpsRequest.builder().pageSize(1).build())+ .stream().flatMap(page -> page.dedicatedIps().stream())).isEmpty();+ }+}diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesSuppressionListPagingTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesSuppressionListPagingTest.javanew file mode 100644index 0000000000..bce7119e74--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesSuppressionListPagingTest.java@@ -0,0 +1,93 @@+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.DeleteSuppressedDestinationRequest;+import software.amazon.awssdk.services.sesv2.model.InvalidNextTokenException;+import software.amazon.awssdk.services.sesv2.model.ListSuppressedDestinationsRequest;+import software.amazon.awssdk.services.sesv2.model.ListSuppressedDestinationsResponse;+import software.amazon.awssdk.services.sesv2.model.PutSuppressedDestinationRequest;+import software.amazon.awssdk.services.sesv2.model.SuppressedDestinationSummary;+import software.amazon.awssdk.services.sesv2.model.SuppressionListReason;++import java.util.ArrayList;+import java.util.List;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++@DisplayName("SES v2 suppression list paging")+class SesSuppressionListPagingTest {++ private static SesV2Client sesV2;+ private static List<String> bounces;+ private static String complaint;++ @BeforeAll+ static void setup() {+ sesV2 = TestFixtures.sesV2Client();+ String prefix = "sdk-page-" + TestFixtures.uniqueName() + "-";+ bounces = List.of(prefix + "[email protected]", prefix + "[email protected]");+ complaint = prefix + "[email protected]";+ for (String address : bounces) {+ put(address, SuppressionListReason.BOUNCE);+ }+ put(complaint, SuppressionListReason.COMPLAINT);+ }++ @AfterAll+ static void cleanup() {+ if (sesV2 != null) {+ List<String> all = new ArrayList<>(bounces);+ all.add(complaint);+ for (String address : all) {+ try {+ sesV2.deleteSuppressedDestination(DeleteSuppressedDestinationRequest.builder()+ .emailAddress(address).build());+ } catch (Exception ignored) {+ // Best-effort cleanup; a leftover destination does not affect other tests.+ }+ }+ sesV2.close();+ }+ }++ @Test+ @DisplayName("Paginator walks one-item pages of one reason over every destination once")+ void paginatorWalksEveryFilteredDestinationOnce() {+ List<String> listed = new ArrayList<>();+ for (ListSuppressedDestinationsResponse page : sesV2.listSuppressedDestinationsPaginator(+ ListSuppressedDestinationsRequest.builder()+ .reasons(SuppressionListReason.BOUNCE).pageSize(1).build())) {+ assertThat(page.suppressedDestinationSummaries()).hasSizeLessThanOrEqualTo(1);+ page.suppressedDestinationSummaries().stream()+ .map(SuppressedDestinationSummary::emailAddress).forEach(listed::add);+ }++ assertThat(listed).doesNotHaveDuplicates().doesNotContain(complaint);+ assertThat(listed.stream().filter(bounces::contains)).containsExactlyInAnyOrderElementsOf(bounces);+ }++ @Test+ @DisplayName("A token taken with one reason filter is refused without it")+ void tokenIsBoundToItsFilter() {+ ListSuppressedDestinationsResponse first = sesV2.listSuppressedDestinations(+ ListSuppressedDestinationsRequest.builder()+ .reasons(SuppressionListReason.BOUNCE).pageSize(1).build());+ assertThat(first.nextToken()).isNotNull();++ assertThatThrownBy(() -> sesV2.listSuppressedDestinations(+ ListSuppressedDestinationsRequest.builder().nextToken(first.nextToken()).build()))+ .isInstanceOf(InvalidNextTokenException.class)+ .hasMessageContaining("Token is invalid.");+ }++ private static void put(String address, SuppressionListReason reason) {+ sesV2.putSuppressedDestination(PutSuppressedDestinationRequest.builder()+ .emailAddress(address).reason(reason).build());+ }+}diff --git a/docs/services/ses.md b/docs/services/ses.mdindex 8cb9e07bd8..2868dc33a3 100644--- a/docs/services/ses.md+++ b/docs/services/ses.md@@ -446,6 +446,8 @@ The template, identity, configuration-set, custom-verification-template and expoThe 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.+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).### IAM enforcementdiff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesContactController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesContactController.javaindex 5cbbc8c873..247f736910 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@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ArrayNode;import com.fasterxml.jackson.databind.node.ObjectNode;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.PaginatedResult;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.services.ses.model.Contact;import io.github.hectorvent.floci.services.ses.model.ContactList;@@ -21,20 +22,24 @@ import jakarta.ws.rs.PUT;import jakarta.ws.rs.Path;import jakarta.ws.rs.PathParam;import jakarta.ws.rs.Produces;+import jakarta.ws.rs.QueryParam;import jakarta.ws.rs.core.Context;import jakarta.ws.rs.core.HttpHeaders;import jakarta.ws.rs.core.MediaType;import jakarta.ws.rs.core.Response;+import jakarta.ws.rs.core.UriInfo;import org.jboss.logging.Logger;import java.util.ArrayList;import java.util.List;import static io.github.hectorvent.floci.services.ses.SesV2Json.coerceBoolean;+import static io.github.hectorvent.floci.services.ses.SesV2Json.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.unexpectedStartError;/**@@ -90,15 +95,21 @@ public class SesContactController {@GET@Path("/contact-lists")- public Response listContactLists(@Context HttpHeaders headers) {+ public Response listContactLists(@Context HttpHeaders headers,+ @QueryParam("PageSize") String pageSize,+ @Context UriInfo uriInfo) {String region = regionResolver.resolveRegion(headers);+ String nextToken = SesListPaging.queryToken(uriInfo);+ PaginatedResult<ContactList> page = contactService.listContactLists(region,+ SesListPaging.V2_LIST_CONTACT_LISTS, SesListPaging.parseQueryPageSize(pageSize), nextToken);ObjectNode result = objectMapper.createObjectNode();ArrayNode lists = result.putArray("ContactLists");- for (ContactList cl : contactService.listContactLists(region)) {+ for (ContactList cl : page.items()) {ObjectNode item = lists.addObject();item.put("ContactListName", cl.getContactListName());putTimestamp(item, "LastUpdatedTimestamp", cl.getLastUpdatedTimestamp());}+ result.put("NextToken", page.nextToken());return Response.ok(result).build();}@@ -226,21 +237,25 @@ 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 returns- // all contacts (filtering/pagination not yet implemented) but still rejects a malformed or- // non-object body like the other v2 endpoints.+ // 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 {- if (body != null && !body.isBlank()) {- requireJsonObject(objectMapper.readTree(body));- }- SesContactService.ContactsWithList listed =- contactService.listContacts(contactListName, region);+ JsonNode request = (body == null || body.isBlank())+ ? objectMapper.createObjectNode()+ : objectMapper.readTree(body);+ requireJsonObject(request);+ Integer pageSize = intMemberOrAbsent(request, "PageSize");+ String nextToken = stringMemberOrAbsent(request, "NextToken");+ SesContactService.ContactPage listed = contactService.listContacts(contactListName, region,+ SesListPaging.V2_LIST_CONTACTS, pageSize, nextToken);ObjectNode result = objectMapper.createObjectNode();ArrayNode arr = result.putArray("Contacts");- for (Contact c : listed.contacts()) {+ for (Contact c : listed.contacts().items()) {arr.add(contactJson(c, listed.list(), false));}+ result.put("NextToken", listed.contacts().nextToken());return Response.ok(result).build();} catch (AwsException e) {throw remapV1Exception(e);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.javaindex 54131e3f29..285d7445a0 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@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ses;import com.fasterxml.jackson.core.type.TypeReference;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.PaginatedResult;import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.ses.model.Contact;@@ -151,6 +152,12 @@ public class SesContactService {"No ContactList present with name: " + name, 404);}+ public PaginatedResult<ContactList> listContactLists(String region, SesListPaging paging, Integer pageSize,+ String nextToken) {+ return paging.page(region, listContactLists(region), ContactList::getContactListName, pageSize,+ nextToken);+ }+public List<ContactList> listContactLists(String region) {String prefix = "contactList::" + region + "::";return contactListStore.scan(k -> k.startsWith(prefix)).stream()@@ -351,14 +358,33 @@ public class SesContactService {return new ContactWithList(contact, list);}+ public record ContactPage(PaginatedResult<Contact> contacts, ContactList list) {+ }++ /** SES reads the page size and the token before it looks the list up. */+ public ContactPage listContacts(String listName, String region, SesListPaging paging, Integer pageSize,+ String nextToken) {+ ContactList list = contactListStore.get(contactListKey(region, listName)).orElse(null);+ List<Contact> contacts = list == null ? List.of() : contactsOf(listName, region);+ PaginatedResult<Contact> page = paging.page(region, contacts, Contact::getEmailAddress, pageSize,+ nextToken);+ if (list == null) {+ throw contactListNotFound(listName);+ }+ return new ContactPage(page, list);+ }+public ContactsWithList listContacts(String listName, String region) {ContactList list = getContactList(listName, region);+ return new ContactsWithList(contactsOf(listName, region), list);+ }++ private List<Contact> contactsOf(String listName, String region) {String prefix = "contact::" + region + "::" + listName + "::";- List<Contact> contacts = contactStore.scan(k -> k.startsWith(prefix)).stream()+ return 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<TopicPreference> topicPreferences,diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpController.javaindex 0bfdbb7223..9beb0b90fd 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpController.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpController.java@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ArrayNode;import com.fasterxml.jackson.databind.node.ObjectNode;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.PaginatedResult;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool;import io.github.hectorvent.floci.services.ses.model.Tag;@@ -18,6 +19,7 @@ import jakarta.ws.rs.PUT;import jakarta.ws.rs.Path;import jakarta.ws.rs.PathParam;import jakarta.ws.rs.Produces;+import jakarta.ws.rs.QueryParam;import jakarta.ws.rs.core.Context;import jakarta.ws.rs.core.HttpHeaders;import jakarta.ws.rs.core.MediaType;@@ -92,11 +94,16 @@ public class SesDedicatedIpController {@GET@Path("/dedicated-ip-pools")- public Response listDedicatedIpPools(@Context HttpHeaders headers) {+ public Response listDedicatedIpPools(@Context HttpHeaders headers,+ @QueryParam("PageSize") String pageSize,+ @QueryParam("NextToken") String nextToken) {String region = regionResolver.resolveRegion(headers);+ PaginatedResult<String> page = dedicatedIpService.listDedicatedIpPools(region,+ SesListPaging.V2_LIST_DEDICATED_IP_POOLS, SesListPaging.parseQueryPageSize(pageSize), nextToken);ObjectNode result = objectMapper.createObjectNode();ArrayNode pools = result.putArray("DedicatedIpPools");- dedicatedIpService.listDedicatedIpPools(region).forEach(pools::add);+ page.items().forEach(pools::add);+ result.put("NextToken", page.nextToken());return Response.ok(result).build();}@@ -144,12 +151,16 @@ public class SesDedicatedIpController {@GET@Path("/dedicated-ips")- public Response getDedicatedIps(@Context HttpHeaders headers) {- regionResolver.resolveRegion(headers);+ public Response getDedicatedIps(@Context HttpHeaders headers,+ @QueryParam("PageSize") String pageSize,+ @QueryParam("NextToken") String nextToken) {+ String region = regionResolver.resolveRegion(headers);// Floci does not model leased dedicated IPs, so the account has none.+ PaginatedResult<String> page = dedicatedIpService.listDedicatedIps(region,+ SesListPaging.V2_GET_DEDICATED_IPS, SesListPaging.parseQueryPageSize(pageSize), nextToken);ObjectNode result = objectMapper.createObjectNode();result.putArray("DedicatedIps");- result.putNull("NextToken");+ result.put("NextToken", page.nextToken());return Response.ok(result).build();}diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpService.javaindex c374312d8b..2f5954f930 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpService.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpService.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ses;import com.fasterxml.jackson.core.type.TypeReference;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.PaginatedResult;import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool;@@ -15,6 +16,7 @@ import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Set;+import java.util.function.Function;/*** Dedicated IP pools (the {@code dedicatedIpPoolStore}), extracted from {@link SesService} as part of@@ -79,6 +81,12 @@ public class SesDedicatedIpService {return dedicatedIpPoolStore.get(dedicatedIpPoolKey(region, poolName)).isPresent();}+ public PaginatedResult<String> listDedicatedIpPools(String region, SesListPaging paging, Integer pageSize,+ String nextToken) {+ return paging.page(region, listDedicatedIpPools(region), Function.identity(), pageSize, nextToken);+ }++ /** By name, the order Floci settles on where SES's own changes with the page size. */public List<String> listDedicatedIpPools(String region) {String prefix = "dedicatedIpPool::" + region + "::";return dedicatedIpPoolStore.scan(k -> k.startsWith(prefix)).stream()@@ -150,6 +158,12 @@ public class SesDedicatedIpService {// IP-targeted operation reports the IP as not found, matching real AWS for an// account with no leased IPs (verified 2026-06-21).+ /** Always empty (see the section note above), but the page size and token are still checked. */+ public PaginatedResult<String> listDedicatedIps(String region, SesListPaging paging, Integer pageSize,+ String nextToken) {+ return paging.page(region, List.<String>of(), Function.identity(), pageSize, nextToken);+ }+private AwsException dedicatedIpNotFound(String ip) {return new AwsException("NotFoundException","Could not find dedicated IP <" + ip + "> under this account.", 404);diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesListPaging.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesListPaging.javaindex e6e3c50522..efbe62acc9 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesListPaging.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesListPaging.java@@ -3,6 +3,7 @@ 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.common.Pagination;+import jakarta.ws.rs.core.UriInfo;import java.time.Instant;import java.util.List;@@ -84,7 +85,44 @@ public enum SesListPaging {* ListImportJobs refuses sandbox accounts, so nothing about it could be probed; it is modelled* on the tenant lists, which share its Smithy-generated validation.*/- V2_LIST_IMPORT_JOBS(Namespace.IMPORT_JOB);+ V2_LIST_IMPORT_JOBS(Namespace.IMPORT_JOB),++ /** SES holds one contact list per region, so no default could be measured; it is taken to be the bound. */+ V2_LIST_CONTACT_LISTS(Namespace.CONTACT_LIST, 1000, 1000,+ size -> badRequest("The page size must be between 1 and 1000"),+ token -> badRequest("Provided NextToken is invalid"),+ true),++ V2_LIST_CONTACTS(Namespace.CONTACT, 50, 1000,+ size -> badRequest("The page size must be between 1 and 1000"),+ token -> badRequest("Provided NextToken is invalid"),+ true),++ /** 12 pools came back whole without a PageSize, so the default is taken to be the bound. */+ V2_LIST_DEDICATED_IP_POOLS(Namespace.DEDICATED_IP_POOL, 1000, 1000,+ size -> badRequest("The page size must be in [1, 1000] range."),+ token -> badRequest("Invalid next token."),+ false),++ /** Unmeasurable without leased IPs; modelled on the pool list, whose messages it shares. */+ V2_GET_DEDICATED_IPS(Namespace.DEDICATED_IP, 1000, 1000,+ size -> badRequest("The page size must be in [1, 1000] range."),+ token -> badRequest("Invalid next token."),+ false),++ /** 24 destinations came back whole without a PageSize, so the default is taken to be the bound. */+ V2_LIST_SUPPRESSED_DESTINATIONS(Namespace.SUPPRESSED_DESTINATION, 1000, 1000,+ size -> badRequest("Page size " + size + " is invalid, expected a number between 1 and 1000"),+ token -> new AwsException("InvalidNextTokenException", "Token is invalid.", 400),+ true),++ /**+ * The request has no size member; the model documents "up to 100 receipt rule sets at a time".+ * SES allows 40 rule sets per region, so a second page could not be observed.+ */+ V1_LIST_RECEIPT_RULE_SETS(Namespace.RECEIPT_RULE_SET, 100, 100, 100,+ token -> invalidParameterValue("Invalid page token: " + token),+ false);private static final class Namespace {static final String TEMPLATE = "template";@@ -96,6 +134,12 @@ public enum SesListPaging {static final String TENANT_RESOURCE = "tenant-resource";static final String RESOURCE_TENANT = "resource-tenant";static final String IMPORT_JOB = "import-job";+ static final String CONTACT_LIST = "contact-list";+ static final String CONTACT = "contact";+ static final String DEDICATED_IP_POOL = "dedicated-ip-pool";+ static final String DEDICATED_IP = "dedicated-ip";+ static final String SUPPRESSED_DESTINATION = "suppressed-destination";+ static final String RECEIPT_RULE_SET = "receipt-rule-set";}/** What the tenant lists share, and ListImportJobs borrows: the bound and Smithy's messages. */@@ -228,6 +272,14 @@ public enum SesListPaging {return time + "#" + id;}+ /**+ * The NextToken of a REST JSON query string, for a list that refuses an empty token: a+ * {@code @QueryParam} binds an empty value as null, which would read as an absent token.+ */+ static String queryToken(UriInfo uriInfo) {+ return uriInfo.getQueryParameters().getFirst("NextToken");+ }+/** A REST JSON query-string page size; a value that is not an int is a serialization error. */static Integer parseQueryPageSize(String raw) {if (raw == null || raw.isEmpty()) {diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.javaindex 63c09050c2..4bd8d6f475 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java@@ -158,7 +158,7 @@ public class SesQueryHandler {handlePutConfigurationSetDeliveryOptions(params, region);case "CreateReceiptRuleSet" -> handleCreateReceiptRuleSet(params, region);case "DescribeReceiptRuleSet" -> handleDescribeReceiptRuleSet(params, region);- case "ListReceiptRuleSets" -> handleListReceiptRuleSets(region);+ case "ListReceiptRuleSets" -> handleListReceiptRuleSets(params, region);case "DeleteReceiptRuleSet" -> handleDeleteReceiptRuleSet(params, region);case "SetActiveReceiptRuleSet" -> handleSetActiveReceiptRuleSet(params, region);case "DescribeActiveReceiptRuleSet" -> handleDescribeActiveReceiptRuleSet(region);@@ -1087,14 +1087,17 @@ public class SesQueryHandler {"DescribeReceiptRuleSet", AwsNamespaces.SES, xml.build())).build();}- private Response handleListReceiptRuleSets(String region) {+ private Response handleListReceiptRuleSets(MultivaluedMap<String, String> params, String region) {+ PaginatedResult<ReceiptRuleSet> page = receiptRuleService.listReceiptRuleSets(region,+ SesListPaging.V1_LIST_RECEIPT_RULE_SETS, getParam(params, "NextToken"));XmlBuilder xml = new XmlBuilder().start("RuleSets");- for (ReceiptRuleSet rs : receiptRuleService.listReceiptRuleSets(region)) {+ for (ReceiptRuleSet rs : page.items()) {xml.start("member");writeReceiptRuleSetMetadataFields(xml, rs);xml.end("member");}xml.end("RuleSets");+ xml.elem("NextToken", page.nextToken());return Response.ok(AwsQueryResponse.envelope("ListReceiptRuleSets", AwsNamespaces.SES, xml.build())).build();}diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleService.javaindex 4d2f3f30c2..6fa5ec9ef0 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleService.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleService.java@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.ses;import com.fasterxml.jackson.core.type.TypeReference;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.PaginatedResult;import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.lambda.LambdaService;@@ -128,12 +129,19 @@ public class SesReceiptRuleService {.orElseThrow(() -> ruleSetDoesNotExist(name));}+ public PaginatedResult<ReceiptRuleSet> listReceiptRuleSets(String region, SesListPaging paging,+ String nextToken) {+ return paging.page(region, listReceiptRuleSets(region), SesReceiptRuleService::cursor, null, nextToken);+ }++ private static String cursor(ReceiptRuleSet ruleSet) {+ return SesListPaging.oldestFirst(ruleSet.getCreatedTimestamp(), ruleSet.getName());+ }+public List<ReceiptRuleSet> listReceiptRuleSets(String region) {String prefix = "receiptRuleSet::" + region + "::";List<ReceiptRuleSet> all = new ArrayList<>(receiptRuleSetStore.scan(k -> k.startsWith(prefix)));- all.sort(Comparator.comparing(ReceiptRuleSet::getCreatedTimestamp,- Comparator.nullsLast(Comparator.naturalOrder()))- .thenComparing(ReceiptRuleSet::getName, Comparator.nullsLast(Comparator.naturalOrder())));+ all.sort(Comparator.comparing(SesReceiptRuleService::cursor));return all;}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.javaindex b1a935bf90..fc6510a4e4 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@@ -1282,6 +1282,19 @@ public class SesService {});}+ public PaginatedResult<SuppressedDestination> listSuppressedDestinations(+ String region, List<String> reasonFilters, String tenantName, SesListPaging paging, Integer pageSize,+ String nextToken) {+ if (tenantName == null) {+ return suppressionService.listSuppressedDestinations(region, reasonFilters, paging, pageSize,+ nextToken);+ }+ SesSuppressionService.validateReasonFilters(reasonFilters);+ return tenantService.runWithTenant(tenantName, region, tenant ->+ suppressionService.listTenantSuppressedDestinations(region, tenant.tenantId(),+ reasonFilters, paging, pageSize, nextToken));+ }+public List<SuppressedDestination> listSuppressedDestinations(String region,List<String> reasonFilters,String tenantName) {diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesSuppressionController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesSuppressionController.javaindex 681df94fde..b84bd6bc2b 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesSuppressionController.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesSuppressionController.java@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ArrayNode;import com.fasterxml.jackson.databind.node.ObjectNode;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.PaginatedResult;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.services.ses.model.SuppressedDestination;import jakarta.inject.Inject;@@ -21,6 +22,7 @@ import jakarta.ws.rs.core.Context;import jakarta.ws.rs.core.HttpHeaders;import jakarta.ws.rs.core.MediaType;import jakarta.ws.rs.core.Response;+import jakarta.ws.rs.core.UriInfo;import org.jboss.logging.Logger;import java.util.List;@@ -121,23 +123,29 @@ public class SesSuppressionController {@Path("/suppression/addresses")public Response listSuppressedDestinations(@Context HttpHeaders headers,@QueryParam("Reason") List<String> reasons,- @QueryParam("TenantName") String tenantName) {+ @QueryParam("TenantName") String tenantName,+ @QueryParam("PageSize") String pageSize,+ @Context UriInfo uriInfo) {String region = regionResolver.resolveRegion(headers);- List<SuppressedDestination> entries;+ String nextToken = SesListPaging.queryToken(uriInfo);+ PaginatedResult<SuppressedDestination> page;try {- entries = sesService.listSuppressedDestinations(region, reasons, tenantName);+ page = sesService.listSuppressedDestinations(region, reasons, tenantName,+ SesListPaging.V2_LIST_SUPPRESSED_DESTINATIONS, SesListPaging.parseQueryPageSize(pageSize),+ nextToken);} catch (AwsException e) {throw remapV1Exception(e);}ObjectNode result = objectMapper.createObjectNode();ArrayNode summaries = result.putArray("SuppressedDestinationSummaries");- for (SuppressedDestination s : entries) {+ for (SuppressedDestination s : page.items()) {ObjectNode item = objectMapper.createObjectNode();item.put("EmailAddress", s.getEmailAddress());item.put("Reason", s.getReason());putTimestamp(item, "LastUpdateTime", s.getLastUpdateTime());summaries.add(item);}+ result.put("NextToken", page.nextToken());return Response.ok(result).build();}}diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesSuppressionService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesSuppressionService.javaindex f88278562e..c277e95b95 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesSuppressionService.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesSuppressionService.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ses;import com.fasterxml.jackson.core.type.TypeReference;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.PaginatedResult;import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.ses.model.AccountSuppressionAttributes;@@ -19,6 +20,7 @@ import java.util.Locale;import java.util.Map;import java.util.Optional;import java.util.Set;+import java.util.TreeSet;/*** Suppression: the account-level suppression attributes and the per-address suppression list,@@ -172,22 +174,41 @@ public class SesSuppressionService {return Optional.empty();}- public List<SuppressedDestination> listSuppressedDestinations(String region, List<String> reasonFilters) {+ /**+ * SES binds the token to the filter it was taken with, so a token replayed with other reasons is+ * refused; its own order is not stable between calls, so Floci keeps oldest first.+ */+ public PaginatedResult<SuppressedDestination> listSuppressedDestinations(+ String region, List<String> reasonFilters, SesListPaging paging, Integer pageSize, String nextToken) {Set<String> filters = validateReasonFilters(reasonFilters);String prefix = "suppression::" + region + "::";- List<SuppressedDestination> all = new ArrayList<>(suppressionStore.scan(k -> k.startsWith(prefix)));- all.sort(Comparator.comparing(SuppressedDestination::getLastUpdateTime,- Comparator.nullsLast(Comparator.naturalOrder()))- .thenComparing(SuppressedDestination::getEmailAddress,- Comparator.nullsLast(Comparator.naturalOrder())));- if (filters.isEmpty()) {- return all;- }- return all.stream()- .filter(s -> filters.contains(s.getReason()))+ return paging.page(region, tokenScope("", filters),+ oldestFirst(suppressionStore.scan(k -> k.startsWith(prefix)), filters),+ SesSuppressionService::cursor, pageSize, nextToken);+ }++ private static String tokenScope(String tenantId, Set<String> filters) {+ return tenantId + "/" + String.join(",", new TreeSet<>(filters));+ }++ private static String cursor(SuppressedDestination destination) {+ return SesListPaging.oldestFirst(destination.getLastUpdateTime(), destination.getEmailAddress());+ }++ private static List<SuppressedDestination> oldestFirst(List<SuppressedDestination> entries,+ Set<String> filters) {+ return entries.stream()+ .filter(s -> filters.isEmpty() || filters.contains(s.getReason()))+ .sorted(Comparator.comparing(SesSuppressionService::cursor)).toList();}+ public List<SuppressedDestination> listSuppressedDestinations(String region, List<String> reasonFilters) {+ Set<String> filters = validateReasonFilters(reasonFilters);+ String prefix = "suppression::" + region + "::";+ return oldestFirst(suppressionStore.scan(k -> k.startsWith(prefix)), filters);+ }+private static String suppressionKey(String region, String emailAddress) {return "suppression::" + region + "::" + emailAddress;}@@ -230,22 +251,21 @@ public class SesSuppressionService {LOG.infov("Removed tenant suppression entry for {0} in region {1}", normalized, region);}+ public PaginatedResult<SuppressedDestination> listTenantSuppressedDestinations(+ String region, String tenantId, List<String> reasonFilters, SesListPaging paging, Integer pageSize,+ String nextToken) {+ Set<String> filters = validateReasonFilters(reasonFilters);+ String prefix = tenantSuppressionKeyPrefix(region, tenantId);+ return paging.page(region, tokenScope(tenantId, filters),+ oldestFirst(tenantSuppressionStore.scan(k -> k.startsWith(prefix)), filters),+ SesSuppressionService::cursor, pageSize, nextToken);+ }+public List<SuppressedDestination> listTenantSuppressedDestinations(String region, String tenantId,List<String> reasonFilters) {Set<String> filters = validateReasonFilters(reasonFilters);String prefix = tenantSuppressionKeyPrefix(region, tenantId);- List<SuppressedDestination> all =- new ArrayList<>(tenantSuppressionStore.scan(k -> k.startsWith(prefix)));- all.sort(Comparator.comparing(SuppressedDestination::getLastUpdateTime,- Comparator.nullsLast(Comparator.naturalOrder()))- .thenComparing(SuppressedDestination::getEmailAddress,- Comparator.nullsLast(Comparator.naturalOrder())));- if (filters.isEmpty()) {- return all;- }- return all.stream()- .filter(s -> filters.contains(s.getReason()))- .toList();+ return oldestFirst(tenantSuppressionStore.scan(k -> k.startsWith(prefix)), filters);}/** DeleteTenant's cascade for this domain, run from inside the tenant lock. */diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesContactPagingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesContactPagingIntegrationTest.javanew file mode 100644index 0000000000..1b0776b99b--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesContactPagingIntegrationTest.java@@ -0,0 +1,136 @@+package io.github.hectorvent.floci.services.ses;++import io.quarkus.test.junit.QuarkusTest;+import io.restassured.response.ValidatableResponse;+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.contains;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasKey;+import static org.hamcrest.Matchers.hasSize;+import static org.hamcrest.Matchers.notNullValue;+import static org.hamcrest.Matchers.nullValue;++/**+ * Paging of {@code ListContactLists} and {@code ListContacts}. Runs in its own region so the one+ * contact list a region may hold is the list created here.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class SesContactPagingIntegrationTest {++ private static final String AUTH =+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/ap-northeast-2/ses/aws4_request";+ private static final String OTHER_REGION_AUTH =+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/eu-north-1/ses/aws4_request";+ private static final String LIST = "page-list";+ private static final String CONTACTS = "/v2/email/contact-lists/" + LIST + "/contacts";++ @Test+ @Order(1)+ void createAListAndContactsOutOfAddressOrder() {+ given().contentType("application/json").header("Authorization", AUTH)+ .body("{\"ContactListName\":\"" + LIST + "\"}")+ .when().post("/v2/email/contact-lists").then().statusCode(200);+ for (String name : new String[] {"page-b", "page-c", "page-a"}) {+ create(name);+ }+ }++ @Test+ @Order(2)+ void contacts_walkByAddressAndEndOnANullToken() {+ String token = list("{\"PageSize\":1}").statusCode(200)+ .body("Contacts.EmailAddress", contains("[email protected]"))+ .body("NextToken", notNullValue())+ .extract().path("NextToken");++ list("{\"PageSize\":2,\"NextToken\":\"" + token + "\"}").statusCode(200)+ .body("Contacts.EmailAddress", contains("[email protected]", "[email protected]"))+ .body("$", hasKey("NextToken"))+ .body("NextToken", nullValue());+ }++ @Test+ @Order(3)+ void contacts_outOfRangeSizesAndUnreadableTokensAreRefused() {+ for (int size : new int[] {0, 1001}) {+ list("{\"PageSize\":" + size + "}").statusCode(400)+ .body("__type", equalTo("BadRequestException"))+ .body("message", equalTo("The page size must be between 1 and 1000"));+ }+ for (String token : new String[] {"garbage", ""}) {+ list("{\"NextToken\":\"" + token + "\"}").statusCode(400)+ .body("__type", equalTo("BadRequestException"))+ .body("message", equalTo("Provided NextToken is invalid"));+ }+ list("{\"PageSize\":0,\"NextToken\":\"garbage\"}").statusCode(400)+ .body("message", equalTo("The page size must be between 1 and 1000"));+ }++ @Test+ @Order(4)+ void contacts_aTokenIsReadBeforeTheListIsLookedUp() {+ String token = list("{\"PageSize\":1}").statusCode(200).extract().path("NextToken");++ given().contentType("application/json").header("Authorization", OTHER_REGION_AUTH)+ .body("{\"NextToken\":\"" + token + "\"}")+ .when().post(CONTACTS + "/list").then().statusCode(400)+ .body("message", equalTo("Provided NextToken is invalid"));+ given().contentType("application/json").header("Authorization", OTHER_REGION_AUTH).body("{}")+ .when().post(CONTACTS + "/list").then().statusCode(404)+ .body("__type", equalTo("NotFoundException"));+ }++ @Test+ @Order(5)+ void contactLists_pageAndRefuseAContactsToken() {+ given().header("Authorization", AUTH).queryParam("PageSize", 1)+ .when().get("/v2/email/contact-lists").then().statusCode(200)+ .body("ContactLists.ContactListName", contains(LIST))+ .body("$", hasKey("NextToken"))+ .body("NextToken", nullValue());++ given().header("Authorization", AUTH).queryParam("PageSize", 1001)+ .when().get("/v2/email/contact-lists").then().statusCode(400)+ .body("message", equalTo("The page size must be between 1 and 1000"));+ String contactsToken = list("{\"PageSize\":1}").statusCode(200).extract().path("NextToken");+ for (String token : new String[] {"garbage", "", contactsToken}) {+ given().header("Authorization", AUTH).queryParam("NextToken", token)+ .when().get("/v2/email/contact-lists").then().statusCode(400)+ .body("__type", equalTo("BadRequestException"))+ .body("message", equalTo("Provided NextToken is invalid"));+ }+ }++ @Test+ @Order(6)+ void contacts_withoutAPageSizeServeFifty() {+ for (int i = 0; i < 48; i++) {+ create("more-%02d".formatted(i));+ }++ String token = list("{}").statusCode(200)+ .body("Contacts", hasSize(50))+ .body("NextToken", notNullValue())+ .extract().path("NextToken");+ list("{\"NextToken\":\"" + token + "\"}").statusCode(200)+ .body("Contacts.EmailAddress", contains("[email protected]"))+ .body("NextToken", nullValue());+ }++ private static void create(String name) {+ given().contentType("application/json").header("Authorization", AUTH)+ .body("{\"EmailAddress\":\"" + name + "@example.com\"}")+ .when().post(CONTACTS).then().statusCode(200);+ }++ private static ValidatableResponse list(String body) {+ return given().contentType("application/json").header("Authorization", AUTH).body(body)+ .when().post(CONTACTS + "/list").then();+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpPagingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpPagingIntegrationTest.javanew file mode 100644index 0000000000..755bbd4091--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpPagingIntegrationTest.java@@ -0,0 +1,102 @@+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.contains;+import static org.hamcrest.Matchers.empty;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasKey;+import static org.hamcrest.Matchers.notNullValue;+import static org.hamcrest.Matchers.nullValue;++/**+ * Paging of {@code ListDedicatedIpPools} and {@code GetDedicatedIps}. Runs in its own region so+ * the pools created here are the whole list.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class SesDedicatedIpPagingIntegrationTest {++ private static final String AUTH =+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/ap-northeast-3/ses/aws4_request";+ private static final String OTHER_REGION_AUTH =+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/eu-north-1/ses/aws4_request";+ private static final String POOLS = "/v2/email/dedicated-ip-pools";+ private static final String IPS = "/v2/email/dedicated-ips";++ @Test+ @Order(1)+ void createPoolsOutOfNameOrder() {+ for (String name : new String[] {"page-b", "page-c", "page-a"}) {+ given().contentType("application/json").header("Authorization", AUTH)+ .body("{\"PoolName\": \"" + name + "\"}")+ .when().post(POOLS).then().statusCode(200);+ }+ }++ @Test+ @Order(2)+ void pools_walkByNameAndEndOnANullToken() {+ String token = given().header("Authorization", AUTH).queryParam("PageSize", 1)+ .when().get(POOLS).then().statusCode(200)+ .body("DedicatedIpPools", contains("page-a"))+ .body("NextToken", notNullValue())+ .extract().path("NextToken");++ given().header("Authorization", AUTH).queryParam("PageSize", 2).queryParam("NextToken", token)+ .when().get(POOLS).then().statusCode(200)+ .body("DedicatedIpPools", contains("page-b", "page-c"))+ .body("$", hasKey("NextToken"))+ .body("NextToken", nullValue());+ }++ @Test+ @Order(3)+ void pools_outOfRangeSizesAndUnreadableTokensAreRefused() {+ for (int size : new int[] {0, 1001}) {+ given().header("Authorization", AUTH).queryParam("PageSize", size)+ .when().get(POOLS).then().statusCode(400)+ .body("__type", equalTo("BadRequestException"))+ .body("message", equalTo("The page size must be in [1, 1000] range."));+ }+ given().header("Authorization", AUTH).queryParam("NextToken", "garbage")+ .when().get(POOLS).then().statusCode(400)+ .body("message", equalTo("Invalid next token."));+ given().header("Authorization", AUTH).queryParam("NextToken", "")+ .when().get(POOLS).then().statusCode(200)+ .body("DedicatedIpPools", contains("page-a", "page-b", "page-c"));+ }++ @Test+ @Order(4)+ void aPoolTokenIsRefusedInAnotherRegionAndByTheIpList() {+ String token = given().header("Authorization", AUTH).queryParam("PageSize", 1)+ .when().get(POOLS).then().statusCode(200).extract().path("NextToken");++ given().header("Authorization", OTHER_REGION_AUTH).queryParam("NextToken", token)+ .when().get(POOLS).then().statusCode(400)+ .body("message", equalTo("Invalid next token."));+ given().header("Authorization", AUTH).queryParam("NextToken", token)+ .when().get(IPS).then().statusCode(400)+ .body("message", equalTo("Invalid next token."));+ }++ @Test+ @Order(5)+ void dedicatedIps_areEmptyButStillCheckThePageSize() {+ given().header("Authorization", AUTH).queryParam("PageSize", 1)+ .when().get(IPS).then().statusCode(200)+ .body("DedicatedIps", empty())+ .body("$", hasKey("NextToken"))+ .body("NextToken", nullValue());+ given().header("Authorization", AUTH).queryParam("PageSize", 1001)+ .when().get(IPS).then().statusCode(400)+ .body("__type", equalTo("BadRequestException"))+ .body("message", equalTo("The page size must be in [1, 1000] range."));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesListPagingTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesListPagingTest.javaindex 5b25935b42..a112357cdb 100644--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesListPagingTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesListPagingTest.java@@ -133,6 +133,27 @@ class SesListPagingTest {assertThat(page(SesListPaging.V1_LIST_IDENTITIES, 1, token).items(), contains("b"));}+ @Test+ void aTokenFromAnotherScope_isRefusedAsUnreadable() {+ SesListPaging paging = SesListPaging.V2_LIST_SUPPRESSED_DESTINATIONS;+ String token = paging.page(REGION, "BOUNCE", ITEMS, Function.identity(), 1, null).nextToken();++ assertThat(paging.page(REGION, "BOUNCE", ITEMS, Function.identity(), 1, token).items(), contains("b"));+ assertError("InvalidNextTokenException", "Token is invalid.",+ () -> paging.page(REGION, "COMPLAINT", ITEMS, Function.identity(), 1, token));+ assertError("InvalidNextTokenException", "Token is invalid.",+ () -> paging.page(REGION, ITEMS, Function.identity(), 1, token));+ }++ @Test+ void contactsDefaultToFiftyAndTheUnmeasuredListsToTheirBound() {+ assertEquals(50, SesListPaging.V2_LIST_CONTACTS.pageSize(null));+ assertEquals(1000, SesListPaging.V2_LIST_CONTACT_LISTS.pageSize(null));+ assertEquals(1000, SesListPaging.V2_LIST_DEDICATED_IP_POOLS.pageSize(null));+ assertEquals(1000, SesListPaging.V2_GET_DEDICATED_IPS.pageSize(null));+ assertEquals(1000, SesListPaging.V2_LIST_SUPPRESSED_DESTINATIONS.pageSize(null));+ }+@Testvoid invalidToken_messagesQuoteTheToken() {assertError("BadRequestException", "Invalid PageToken <garbage>.",diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleServiceTest.javaindex 33e1c6a1ca..941e084f65 100644--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleServiceTest.java@@ -1,6 +1,7 @@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.lambda.LambdaService;import io.github.hectorvent.floci.services.s3.S3Service;@@ -20,6 +21,7 @@ import java.util.function.Predicate;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.anyString;@@ -883,4 +885,24 @@ class SesReceiptRuleServiceTest {assertEquals("LimitExceeded", e.getErrorCode());assertEquals("Too many filters", e.getMessage());}++ @Test+ void listReceiptRuleSets_servesAHundredAPageAndResumesFromTheToken() {+ for (int i = 0; i < 101; i++) {+ service.createReceiptRuleSet("page-%03d".formatted(i), REGION);+ }++ PaginatedResult<ReceiptRuleSet> first = service.listReceiptRuleSets(REGION,+ SesListPaging.V1_LIST_RECEIPT_RULE_SETS, null);+ assertEquals(100, first.items().size());+ PaginatedResult<ReceiptRuleSet> rest = service.listReceiptRuleSets(REGION,+ SesListPaging.V1_LIST_RECEIPT_RULE_SETS, first.nextToken());+ assertEquals(1, rest.items().size());+ assertNull(rest.nextToken());++ List<String> paged = new ArrayList<>();+ first.items().forEach(ruleSet -> paged.add(ruleSet.getName()));+ rest.items().forEach(ruleSet -> paged.add(ruleSet.getName()));+ assertEquals(service.listReceiptRuleSets(REGION).stream().map(ReceiptRuleSet::getName).toList(), paged);+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleSetPagingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleSetPagingIntegrationTest.javanew file mode 100644index 0000000000..4146f6693f--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleSetPagingIntegrationTest.java@@ -0,0 +1,72 @@+package io.github.hectorvent.floci.services.ses;++import io.quarkus.test.junit.QuarkusTest;+import io.restassured.path.xml.XmlPath;+import io.restassured.specification.RequestSpecification;+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 java.util.ArrayList;+import java.util.List;++import static io.restassured.RestAssured.given;+import static org.hamcrest.MatcherAssert.assertThat;+import static org.hamcrest.Matchers.contains;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.emptyOrNullString;+import static org.hamcrest.Matchers.hasSize;+import static org.hamcrest.Matchers.not;+import static org.junit.jupiter.api.Assertions.assertEquals;++/**+ * Paging of v1 {@code ListReceiptRuleSets} on the Query wire: 100 rule sets a page and a token on+ * every page but the last. Runs in its own region so the rule sets created here are the whole list.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class SesReceiptRuleSetPagingIntegrationTest {++ private static final String AUTH =+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/il-central-1/email/aws4_request";+ private static final String ROOT = "ListReceiptRuleSetsResponse.ListReceiptRuleSetsResult.";++ @Test+ @Order(1)+ void createAHundredAndOneRuleSets() {+ for (int i = 0; i < 101; i++) {+ req("CreateReceiptRuleSet").formParam("RuleSetName", "page-%03d".formatted(i))+ .when().post("/").then().statusCode(200);+ }+ }++ @Test+ @Order(2)+ void servesAHundredThenTheRestOldestFirstAndOmitsTheTokenOnTheLastPage() {+ XmlPath first = req("ListReceiptRuleSets").when().post("/").then().statusCode(200)+ .extract().xmlPath();+ List<String> names = new ArrayList<>(first.getList(ROOT + "RuleSets.member.Name"));+ assertThat(names, hasSize(100));+ String token = first.getString(ROOT + "NextToken");+ assertThat(token, not(emptyOrNullString()));++ XmlPath rest = req("ListReceiptRuleSets").formParam("NextToken", token)+ .when().post("/").then().statusCode(200)+ .body(not(containsString("<NextToken>")))+ .extract().xmlPath();+ assertThat(rest.getList(ROOT + "RuleSets.member.Name"), contains("page-100"));+ names.addAll(rest.getList(ROOT + "RuleSets.member.Name"));++ List<String> created = new ArrayList<>();+ for (int i = 0; i < 101; i++) {+ created.add("page-%03d".formatted(i));+ }+ assertEquals(created, names);+ }++ private static RequestSpecification req(String action) {+ return given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH)+ .formParam("Action", action);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleSetV1IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleSetV1IntegrationTest.javaindex d77ee18a13..f2c54615ae 100644--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleSetV1IntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleSetV1IntegrationTest.java@@ -68,6 +68,18 @@ class SesReceiptRuleSetV1IntegrationTest {.body(containsString("<Name>" + RS + "</Name>"));}+ // Unordered on purpose: it holds whether or not the rule set above still exists.+ @Test+ void listReceiptRuleSets_treatsAnEmptyTokenAsAbsentAndRefusesAnyOther() {+ req("ListReceiptRuleSets").formParam("NextToken", "")+ .when().post("/").then().statusCode(200)+ .body(containsString("ListReceiptRuleSetsResponse"));+ req("ListReceiptRuleSets").formParam("NextToken", "garbage")+ .when().post("/").then().statusCode(400)+ .body(containsString("<Code>InvalidParameterValue</Code>"))+ .body(containsString("<Message>Invalid page token: garbage</Message>"));+ }+@Test@Order(5)void describeNonExistent_returnsRuleSetDoesNotExist() {diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesSuppressedDestinationPagingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesSuppressedDestinationPagingIntegrationTest.javanew file mode 100644index 0000000000..fb71254b3f--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesSuppressedDestinationPagingIntegrationTest.java@@ -0,0 +1,142 @@+package io.github.hectorvent.floci.services.ses;++import io.quarkus.test.junit.QuarkusTest;+import io.restassured.specification.RequestSpecification;+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.contains;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasKey;+import static org.hamcrest.Matchers.notNullValue;+import static org.hamcrest.Matchers.nullValue;++/**+ * Paging of {@code ListSuppressedDestinations}, on the account list and on a tenant's. Runs in its+ * own region so the destinations created here are the whole list.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class SesSuppressedDestinationPagingIntegrationTest {++ private static final String AUTH =+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/me-south-1/ses/aws4_request";+ private static final String OTHER_REGION_AUTH =+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/eu-north-1/ses/aws4_request";+ private static final String PATH = "/v2/email/suppression/addresses";+ private static final String ADDRESSES = "SuppressedDestinationSummaries.EmailAddress";+ private static final String TENANT = "page-tenant";++ // Put in address order, so oldest first and the address tie-break agree whatever the clock does.+ @Test+ @Order(1)+ void suppressDestinations() {+ put("[email protected]", "BOUNCE", null);+ put("[email protected]", "COMPLAINT", null);+ put("[email protected]", "BOUNCE", null);+ put("[email protected]", "BOUNCE", null);+ }++ @Test+ @Order(2)+ void walksOldestFirstAndEndsOnANullToken() {+ String token = v2().queryParam("PageSize", 1)+ .when().get(PATH).then().statusCode(200)+ .body(ADDRESSES, contains("[email protected]"))+ .body("NextToken", notNullValue())+ .extract().path("NextToken");++ v2().queryParam("PageSize", 3).queryParam("NextToken", token)+ .when().get(PATH).then().statusCode(200)+ .body("$", hasKey("NextToken"))+ .body("NextToken", nullValue());+ }++ @Test+ @Order(3)+ void theReasonFilterIsAppliedBeforeThePageIsCut() {+ String token = v2().queryParam("Reason", "BOUNCE").queryParam("PageSize", 2)+ .when().get(PATH).then().statusCode(200)+ .body(ADDRESSES, contains("[email protected]", "[email protected]"))+ .extract().path("NextToken");++ v2().queryParam("Reason", "BOUNCE").queryParam("PageSize", 2).queryParam("NextToken", token)+ .when().get(PATH).then().statusCode(200)+ .body(ADDRESSES, contains("[email protected]"))+ .body("NextToken", nullValue());+ }++ @Test+ @Order(4)+ void aTokenIsBoundToItsFilterAndRegion() {+ String token = v2().queryParam("Reason", "BOUNCE").queryParam("PageSize", 1)+ .when().get(PATH).then().statusCode(200).extract().path("NextToken");++ assertTokenRefused(v2().queryParam("NextToken", token));+ assertTokenRefused(v2().queryParam("Reason", "COMPLAINT").queryParam("NextToken", token));+ assertTokenRefused(given().header("Authorization", OTHER_REGION_AUTH)+ .queryParam("Reason", "BOUNCE").queryParam("NextToken", token));+ }++ @Test+ @Order(5)+ void outOfRangeSizesAndUnreadableTokensAreRefused() {+ for (int size : new int[] {0, 1001}) {+ v2().queryParam("PageSize", size)+ .when().get(PATH).then().statusCode(400)+ .body("__type", equalTo("BadRequestException"))+ .body("message", equalTo(+ "Page size " + size + " is invalid, expected a number between 1 and 1000"));+ }+ assertTokenRefused(v2().queryParam("NextToken", "garbage"));+ assertTokenRefused(v2().queryParam("NextToken", ""));+ v2().queryParam("PageSize", 0).queryParam("NextToken", "garbage")+ .when().get(PATH).then().statusCode(400)+ .body("message", equalTo("Page size 0 is invalid, expected a number between 1 and 1000"));+ }++ @Test+ @Order(6)+ void aTenantListPagesOnItsOwnTokens() {+ given().contentType("application/json").header("Authorization", AUTH)+ .body("{\"TenantName\":\"" + TENANT + "\"}")+ .when().post("/v2/email/tenants").then().statusCode(200);+ put("[email protected]", "BOUNCE", TENANT);+ put("[email protected]", "BOUNCE", TENANT);++ String tenantToken = v2().queryParam("TenantName", TENANT).queryParam("PageSize", 1)+ .when().get(PATH).then().statusCode(200)+ .body(ADDRESSES, contains("[email protected]"))+ .extract().path("NextToken");+ v2().queryParam("TenantName", TENANT).queryParam("NextToken", tenantToken)+ .when().get(PATH).then().statusCode(200)+ .body(ADDRESSES, contains("[email protected]"))+ .body("NextToken", nullValue());++ assertTokenRefused(v2().queryParam("NextToken", tenantToken));+ String accountToken = v2().queryParam("PageSize", 1)+ .when().get(PATH).then().statusCode(200).extract().path("NextToken");+ assertTokenRefused(v2().queryParam("TenantName", TENANT).queryParam("NextToken", accountToken));+ }++ private static void assertTokenRefused(RequestSpecification request) {+ request.when().get(PATH).then().statusCode(400)+ .body("__type", equalTo("InvalidNextTokenException"))+ .body("message", equalTo("Token is invalid."));+ }++ private static RequestSpecification v2() {+ return given().header("Authorization", AUTH);+ }++ private static void put(String address, String reason, String tenant) {+ String tenantMember = tenant == null ? "" : ",\"TenantName\":\"" + tenant + "\"";+ given().contentType("application/json").header("Authorization", AUTH)+ .body("{\"EmailAddress\":\"" + address + "\",\"Reason\":\"" + reason + "\"" + tenantMember + "}")+ .when().put(PATH).then().statusCode(200);+ }+}