From ea41b775aa0c442c951557a14add9b0c25ee5a66 Mon Sep 17 00:00:00 2001 From: Kenshin Okinaka Date: Thu, 1 Oct 2026 13:29:35 +0900 Subject: [PATCH] feat(ses): paginate the identity, configuration set and custom verification template lists (#4781) * feat(ses): paginate the identity, configuration set and custom verification template lists Move paging into the SES services, so each resource's cursor lives with its list and the v1 and v2 operations of the same resource share it. Page ListIdentities/ListEmailIdentities, ListConfigurationSets (v1 and v2) and ListCustomVerificationEmailTemplates (v1 and v2) with the probed defaults, bounds and messages: identities default to 25 on v2, configuration sets and custom verification templates to 50, and a v1 page size outside the bound is served the probed size instead of refused. * fix(ses): refuse a list token replayed in another region A list token carried only the resource kind and the cursor, so the same list in another region read it as a position and could answer an empty last page. Real SES refuses such a token with the operation's unreadable-token error (probed on the identity and configuration-set lists), so the token namespace now includes the region. The v1 and v2 lists of one resource still share tokens within a region. --- .../test/SesConfigurationSetPagingTest.java | 105 ++++++++++ .../floci/test/SesConfigurationSetTest.java | 5 +- ...omVerificationEmailTemplatePagingTest.java | 116 ++++++++++++ .../floci/test/SesIdentityAttributesTest.java | 3 +- .../com/floci/test/SesIdentityPagingTest.java | 102 ++++++++++ docs/services/ses.md | 2 +- .../ses/SesConfigurationSetController.java | 12 +- .../ses/SesConfigurationSetService.java | 16 +- .../floci/services/ses/SesCvetController.java | 15 +- .../floci/services/ses/SesCvetService.java | 8 + .../services/ses/SesExportJobController.java | 6 +- .../services/ses/SesExportJobService.java | 15 ++ .../services/ses/SesIdentityController.java | 12 +- .../services/ses/SesIdentityService.java | 24 ++- .../floci/services/ses/SesListPaging.java | 81 ++++++-- .../floci/services/ses/SesQueryHandler.java | 40 ++-- .../services/ses/SesTemplateController.java | 5 +- .../services/ses/SesTemplateService.java | 16 +- ...ConfigurationSetPagingIntegrationTest.java | 147 ++++++++++++++ .../ses/SesConfigurationSetServiceTest.java | 10 +- ...ionEmailTemplatePagingIntegrationTest.java | 161 ++++++++++++++++ .../ses/SesIdentityPagingIntegrationTest.java | 179 ++++++++++++++++++ .../services/ses/SesIdentityServiceTest.java | 3 +- .../floci/services/ses/SesListPagingTest.java | 82 +++++++- .../services/ses/SesTemplateServiceTest.java | 17 +- .../services/ses/SesV2IntegrationTest.java | 2 + 26 files changed, 1099 insertions(+), 85 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetPagingTest.java create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesCustomVerificationEmailTemplatePagingTest.java create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesIdentityPagingTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetPagingIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ses/SesCustomVerificationEmailTemplatePagingIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityPagingIntegrationTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetPagingTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetPagingTest.java new file mode 100644 index 0000000000..b567ee6387 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetPagingTest.java @@ -0,0 +1,105 @@ +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.ses.SesClient; +import software.amazon.awssdk.services.ses.model.ConfigurationSet; +import software.amazon.awssdk.services.ses.model.ListConfigurationSetsRequest; +import software.amazon.awssdk.services.ses.model.ListConfigurationSetsResponse; +import software.amazon.awssdk.services.sesv2.SesV2Client; +import software.amazon.awssdk.services.sesv2.model.CreateConfigurationSetRequest; +import software.amazon.awssdk.services.sesv2.model.DeleteConfigurationSetRequest; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +// The v1 and v2 SDKs both define ListConfigurationSetsRequest/Response: v1's are imported, v2's qualified. +@DisplayName("SES configuration set list paging") +class SesConfigurationSetPagingTest { + + private static SesClient sesV1; + private static SesV2Client sesV2; + private static List names; + + @BeforeAll + static void setup() { + sesV1 = TestFixtures.sesClient(); + sesV2 = TestFixtures.sesV2Client(); + String prefix = "sdk-page-" + TestFixtures.uniqueName() + "-"; + names = List.of(prefix + "b", prefix + "c", prefix + "a"); + for (String name : names) { + sesV2.createConfigurationSet(CreateConfigurationSetRequest.builder() + .configurationSetName(name).build()); + } + } + + @AfterAll + static void cleanup() { + if (sesV2 != null) { + for (String name : names) { + try { + sesV2.deleteConfigurationSet(DeleteConfigurationSetRequest.builder() + .configurationSetName(name).build()); + } catch (Exception ignored) { + // Best-effort cleanup; a leftover configuration set does not affect other tests. + } + } + sesV2.close(); + } + if (sesV1 != null) { + sesV1.close(); + } + } + + @Test + @DisplayName("V2 paginator walks one-item pages over every configuration set once") + void v2PaginatorWalksEveryConfigurationSetOnce() { + List listed = new ArrayList<>(); + for (software.amazon.awssdk.services.sesv2.model.ListConfigurationSetsResponse page + : sesV2.listConfigurationSetsPaginator( + software.amazon.awssdk.services.sesv2.model.ListConfigurationSetsRequest.builder() + .pageSize(1).build())) { + assertThat(page.configurationSets()).hasSizeLessThanOrEqualTo(1); + listed.addAll(page.configurationSets()); + } + + assertThat(listed).doesNotHaveDuplicates(); + assertThat(listed.stream().filter(names::contains)).containsExactlyInAnyOrderElementsOf(names); + } + + @Test + @DisplayName("V1 MaxItems pages over every configuration set once and ends without a token") + void v1PagesOverEveryConfigurationSetOnce() { + List listed = new ArrayList<>(); + String token = null; + do { + ListConfigurationSetsResponse page = sesV1.listConfigurationSets(ListConfigurationSetsRequest.builder() + .maxItems(1).nextToken(token).build()); + assertThat(page.configurationSets()).hasSizeLessThanOrEqualTo(1); + page.configurationSets().stream().map(ConfigurationSet::name).forEach(listed::add); + token = page.nextToken(); + } while (token != null); + + assertThat(listed).doesNotHaveDuplicates(); + assertThat(listed.stream().filter(names::contains)).containsExactlyInAnyOrderElementsOf(names); + } + + @Test + @DisplayName("A V1 token continues the V2 list") + void v1TokenContinuesTheV2List() { + ListConfigurationSetsResponse first = sesV1.listConfigurationSets(ListConfigurationSetsRequest.builder() + .maxItems(1).build()); + assertThat(first.nextToken()).isNotNull(); + + software.amazon.awssdk.services.sesv2.model.ListConfigurationSetsResponse rest = + sesV2.listConfigurationSets(software.amazon.awssdk.services.sesv2.model.ListConfigurationSetsRequest + .builder().nextToken(first.nextToken()).build()); + + assertThat(rest.configurationSets()).doesNotContain(first.configurationSets().get(0).name()); + } +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetTest.java index 8c44927a9a..794e8d43f6 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetTest.java @@ -108,7 +108,8 @@ class SesConfigurationSetTest { @Order(4) void v2ListConfigurationSetsIncludesCreated() { software.amazon.awssdk.services.sesv2.model.ListConfigurationSetsResponse response = - sesV2.listConfigurationSets(software.amazon.awssdk.services.sesv2.model.ListConfigurationSetsRequest.builder().build()); + sesV2.listConfigurationSets(software.amazon.awssdk.services.sesv2.model.ListConfigurationSetsRequest.builder() + .pageSize(1000).build()); assertThat(response.configurationSets()).contains(v2Name); } @@ -169,7 +170,7 @@ class SesConfigurationSetTest { @Order(13) void v1ListConfigurationSetsIncludesCreated() { ListConfigurationSetsResponse response = sesV1.listConfigurationSets( - ListConfigurationSetsRequest.builder().build()); + ListConfigurationSetsRequest.builder().maxItems(1000).build()); assertThat(response.configurationSets()) .anyMatch(cs -> v1Name.equals(cs.name())); } diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesCustomVerificationEmailTemplatePagingTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesCustomVerificationEmailTemplatePagingTest.java new file mode 100644 index 0000000000..64171ff70b --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesCustomVerificationEmailTemplatePagingTest.java @@ -0,0 +1,116 @@ +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.ses.SesClient; +import software.amazon.awssdk.services.ses.model.CustomVerificationEmailTemplate; +import software.amazon.awssdk.services.ses.model.ListCustomVerificationEmailTemplatesRequest; +import software.amazon.awssdk.services.ses.model.ListCustomVerificationEmailTemplatesResponse; +import software.amazon.awssdk.services.sesv2.SesV2Client; +import software.amazon.awssdk.services.sesv2.model.CreateEmailIdentityRequest; +import software.amazon.awssdk.services.sesv2.model.CustomVerificationEmailTemplateMetadata; +import software.amazon.awssdk.services.sesv2.model.DeleteEmailIdentityRequest; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +// The v1 and v2 SDKs both define ListCustomVerificationEmailTemplatesResponse: v1's is imported, v2's qualified. +@DisplayName("SES custom verification email template list paging") +class SesCustomVerificationEmailTemplatePagingTest { + + private static SesClient sesV1; + private static SesV2Client sesV2; + private static String from; + private static List names; + + @BeforeAll + static void setup() { + sesV1 = TestFixtures.sesClient(); + sesV2 = TestFixtures.sesV2Client(); + String prefix = "sdk-page-" + TestFixtures.uniqueName() + "-"; + from = prefix + "sender@floci-cvet.test"; + names = List.of(prefix + "b", prefix + "c", prefix + "a"); + sesV2.createEmailIdentity(CreateEmailIdentityRequest.builder().emailIdentity(from).build()); + for (String name : names) { + sesV2.createCustomVerificationEmailTemplate(b -> b + .templateName(name).fromEmailAddress(from).templateSubject("Verify") + .templateContent("verify") + .successRedirectionURL("https://example.com/ok") + .failureRedirectionURL("https://example.com/fail")); + } + } + + @AfterAll + static void cleanup() { + if (sesV2 != null) { + for (String name : names) { + try { + sesV2.deleteCustomVerificationEmailTemplate(b -> b.templateName(name)); + } catch (Exception ignored) { + // Best-effort cleanup; a leftover template does not affect other tests. + } + } + try { + sesV2.deleteEmailIdentity(DeleteEmailIdentityRequest.builder().emailIdentity(from).build()); + } catch (Exception ignored) { + // Best-effort cleanup; a leftover identity does not affect other tests. + } + sesV2.close(); + } + if (sesV1 != null) { + sesV1.close(); + } + } + + @Test + @DisplayName("V2 paginator walks one-item pages over every template once") + void v2PaginatorWalksEveryTemplateOnce() { + List listed = new ArrayList<>(); + for (software.amazon.awssdk.services.sesv2.model.ListCustomVerificationEmailTemplatesResponse page + : sesV2.listCustomVerificationEmailTemplatesPaginator(b -> b.pageSize(1))) { + assertThat(page.customVerificationEmailTemplates()).hasSizeLessThanOrEqualTo(1); + page.customVerificationEmailTemplates().stream() + .map(CustomVerificationEmailTemplateMetadata::templateName).forEach(listed::add); + } + + assertThat(listed).doesNotHaveDuplicates(); + assertThat(listed.stream().filter(names::contains)).containsExactlyInAnyOrderElementsOf(names); + } + + @Test + @DisplayName("V1 MaxResults pages over every template once and ends without a token") + void v1PagesOverEveryTemplateOnce() { + List listed = new ArrayList<>(); + String token = null; + do { + ListCustomVerificationEmailTemplatesResponse page = sesV1.listCustomVerificationEmailTemplates( + ListCustomVerificationEmailTemplatesRequest.builder().maxResults(1).nextToken(token).build()); + assertThat(page.customVerificationEmailTemplates()).hasSizeLessThanOrEqualTo(1); + page.customVerificationEmailTemplates().stream() + .map(CustomVerificationEmailTemplate::templateName).forEach(listed::add); + token = page.nextToken(); + } while (token != null); + + assertThat(listed).doesNotHaveDuplicates(); + assertThat(listed.stream().filter(names::contains)).containsExactlyInAnyOrderElementsOf(names); + } + + @Test + @DisplayName("A V1 token continues the V2 list") + void v1TokenContinuesTheV2List() { + ListCustomVerificationEmailTemplatesResponse first = sesV1.listCustomVerificationEmailTemplates( + ListCustomVerificationEmailTemplatesRequest.builder().maxResults(1).build()); + assertThat(first.nextToken()).isNotNull(); + + List rest = sesV2.listCustomVerificationEmailTemplates(b -> b.nextToken(first.nextToken())) + .customVerificationEmailTemplates().stream() + .map(CustomVerificationEmailTemplateMetadata::templateName).toList(); + + assertThat(rest).doesNotContain(first.customVerificationEmailTemplates().get(0).templateName()); + } +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesIdentityAttributesTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesIdentityAttributesTest.java index 5901c94e79..9dff8c7e1a 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesIdentityAttributesTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesIdentityAttributesTest.java @@ -222,8 +222,9 @@ class SesIdentityAttributesTest { sesV2.createEmailIdentity(CreateEmailIdentityRequest.builder().emailIdentity(email).build()); sesV2.createEmailIdentity(CreateEmailIdentityRequest.builder().emailIdentity(domain).build()); try { + // Other classes share this Floci, so ask for a page large enough to hold every identity. List identities = sesV2.listEmailIdentities( - ListEmailIdentitiesRequest.builder().build()).emailIdentities(); + ListEmailIdentitiesRequest.builder().pageSize(1000).build()).emailIdentities(); IdentityInfo emailIdentity = identities.stream() .filter(i -> email.equals(i.identityName())).findFirst().orElseThrow(); IdentityInfo domainIdentity = identities.stream() diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesIdentityPagingTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesIdentityPagingTest.java new file mode 100644 index 0000000000..fca962f593 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesIdentityPagingTest.java @@ -0,0 +1,102 @@ +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.ses.SesClient; +import software.amazon.awssdk.services.ses.model.ListIdentitiesRequest; +import software.amazon.awssdk.services.ses.model.ListIdentitiesResponse; +import software.amazon.awssdk.services.sesv2.SesV2Client; +import software.amazon.awssdk.services.sesv2.model.CreateEmailIdentityRequest; +import software.amazon.awssdk.services.sesv2.model.DeleteEmailIdentityRequest; +import software.amazon.awssdk.services.sesv2.model.IdentityInfo; +import software.amazon.awssdk.services.sesv2.model.ListEmailIdentitiesRequest; +import software.amazon.awssdk.services.sesv2.model.ListEmailIdentitiesResponse; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@DisplayName("SES identity list paging") +class SesIdentityPagingTest { + + private static SesClient sesV1; + private static SesV2Client sesV2; + private static List names; + + @BeforeAll + static void setup() { + sesV1 = TestFixtures.sesClient(); + sesV2 = TestFixtures.sesV2Client(); + String prefix = "sdk-page-" + TestFixtures.uniqueName() + "-"; + names = List.of(prefix + "b.test", prefix + "c.test", prefix + "a.test"); + for (String name : names) { + sesV2.createEmailIdentity(CreateEmailIdentityRequest.builder().emailIdentity(name).build()); + } + } + + @AfterAll + static void cleanup() { + if (sesV2 != null) { + for (String name : names) { + try { + sesV2.deleteEmailIdentity(DeleteEmailIdentityRequest.builder().emailIdentity(name).build()); + } catch (Exception ignored) { + // Best-effort cleanup; a leftover identity does not affect other tests. + } + } + sesV2.close(); + } + if (sesV1 != null) { + sesV1.close(); + } + } + + @Test + @DisplayName("V2 paginator walks small pages over every identity once") + void v2PaginatorWalksEveryIdentityOnce() { + List listed = new ArrayList<>(); + for (ListEmailIdentitiesResponse page : sesV2.listEmailIdentitiesPaginator( + ListEmailIdentitiesRequest.builder().pageSize(5).build())) { + assertThat(page.emailIdentities()).hasSizeLessThanOrEqualTo(5); + page.emailIdentities().forEach(identity -> listed.add(identity.identityName())); + } + + assertThat(listed).doesNotHaveDuplicates(); + assertThat(listed.stream().filter(names::contains)).containsExactlyInAnyOrderElementsOf(names); + } + + @Test + @DisplayName("V1 MaxItems pages over every identity once and ends without a token") + void v1PagesOverEveryIdentityOnce() { + List listed = new ArrayList<>(); + String token = null; + do { + ListIdentitiesResponse page = sesV1.listIdentities(ListIdentitiesRequest.builder() + .maxItems(5).nextToken(token).build()); + assertThat(page.identities()).hasSizeLessThanOrEqualTo(5); + listed.addAll(page.identities()); + token = page.nextToken(); + } while (token != null); + + assertThat(listed).doesNotHaveDuplicates(); + assertThat(listed.stream().filter(names::contains)).containsExactlyInAnyOrderElementsOf(names); + } + + @Test + @DisplayName("A V1 token continues the V2 list") + void v1TokenContinuesTheV2List() { + ListIdentitiesResponse first = sesV1.listIdentities(ListIdentitiesRequest.builder() + .maxItems(1).build()); + assertThat(first.nextToken()).isNotNull(); + + ListEmailIdentitiesResponse rest = sesV2.listEmailIdentities(ListEmailIdentitiesRequest.builder() + .nextToken(first.nextToken()).build()); + + assertThat(rest.emailIdentities()).extracting(IdentityInfo::identityName) + .doesNotContain(first.identities().get(0)); + } +} diff --git a/docs/services/ses.md b/docs/services/ses.md index 3dc6f1f439..5548e16b98 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -442,7 +442,7 @@ The same AWS-compatible validation applies wherever tags are set (including `Cre Identity, identity-policy, template, custom-verification-template, configuration-set, and sent-message state is shared between the v1 Query API and the v2 REST JSON API, so a template created with `CreateTemplate` resolves through `SendEmail` on v2 (and vice versa), a policy written with `PutIdentityPolicy` (v1) is returned by `GetEmailIdentityPolicies` (v2), a custom verification email template created with `CreateCustomVerificationEmailTemplate` (v1) is returned by `GetCustomVerificationEmailTemplate` (v2), a configuration set created with `CreateConfigurationSet` is visible to both `DescribeConfigurationSet` (v1) and `GetConfigurationSet` (v2), delivery options written with either `PutConfigurationSetDeliveryOptions` read back through both (v1 spells the policy `Require`/`Optional`, v2 `REQUIRE`/`OPTIONAL`, matching each API), and every send appears in the same `GET /_aws/ses` inspection mailbox. -`ListTemplates`, `ListEmailTemplates` and `ListExportJobs` page with `PageSize` (`MaxItems` on v1) and `NextToken`, newest first, with the page-size bounds and error messages real SES answers (probed 2026-09-25). A token belongs to the kind of resource listed, as on AWS: a v1 `ListTemplates` token continues a v2 `ListEmailTemplates` list and the other way round, while any other list refuses it. Without a page size the template lists serve 10, and a v1 `MaxItems` outside 1 to 100 is served 100 rather than refused, both as on AWS. Floci's own choice: `ListExportJobs` without a `PageSize` serves 100, since AWS documents no default for it. +The template, identity, configuration-set, custom-verification-template and export-job lists page with `PageSize` (`MaxItems` on v1, `MaxResults` for v1 custom verification templates) and `NextToken`, with the page-size bounds and error messages real SES answers (probed 2026-09-25 to 2026-09-27). Templates and export jobs are listed newest first; identities, configuration sets and custom verification templates by name, since SES's own identity order varies between calls and its custom verification template order could not be observed. A token belongs to the kind of resource listed, as on AWS: a v1 token continues the v2 list of the same resources and the other way round, while any other list, and the same list in another region, refuses it. Without a page size the template lists serve 10, `ListEmailIdentities` 25, and the configuration-set and custom-verification-template lists 50, and a v1 page size outside the bound is served 100 on `ListTemplates` and 50 on `ListConfigurationSets` and `ListCustomVerificationEmailTemplates` rather than refused, all as on AWS. Floci's own choices, where AWS documents no default and none could be measured: v1 `ListIdentities` without `MaxItems` serves up to 1000, and `ListExportJobs` without a `PageSize` serves 100. 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 `._domainkey.` 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 `user@example.com` but not `user@mail.example.com` 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/SesConfigurationSetController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetController.java index 124b34c6a7..5844fd8364 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetController.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.ArchivingOptions; import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; @@ -26,6 +27,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; @@ -143,14 +145,18 @@ public class SesConfigurationSetController { @GET @Path("/configuration-sets") - public Response listConfigurationSets(@Context HttpHeaders headers) { + public Response listConfigurationSets(@Context HttpHeaders headers, + @QueryParam("PageSize") String pageSize, + @QueryParam("NextToken") String nextToken) { String region = regionResolver.resolveRegion(headers); - List all = configSetService.list(region); + PaginatedResult page = configSetService.list(region, + SesListPaging.V2_LIST_CONFIGURATION_SETS, SesListPaging.parseQueryPageSize(pageSize), nextToken); ObjectNode result = objectMapper.createObjectNode(); ArrayNode arr = result.putArray("ConfigurationSets"); - for (ConfigurationSet cs : all) { + for (ConfigurationSet cs : page.items()) { arr.add(cs.getName()); } + result.put("NextToken", page.nextToken()); return Response.ok(result).build(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetService.java index 2d738a314c..eaae713d16 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetService.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.ses.model.ArchivingOptions; @@ -128,14 +129,17 @@ public class SesConfigurationSetService { "Configuration set <" + name + "> does not exist.", 400)); } + public PaginatedResult list(String region, SesListPaging paging, Integer pageSize, + String nextToken) { + return paging.page(region, list(region), ConfigurationSet::getName, pageSize, nextToken); + } + + /** By name, as SES lists them; the paged lists resume on the same order. */ public List list(String region) { String prefix = "configSet::" + region + "::"; - List all = new ArrayList<>(configSetStore.scan(k -> k.startsWith(prefix))); - all.sort(Comparator.comparing(ConfigurationSet::getCreatedTimestamp, - Comparator.nullsLast(Comparator.naturalOrder())) - .thenComparing(ConfigurationSet::getName, - Comparator.nullsLast(Comparator.naturalOrder()))); - return all; + return configSetStore.scan(k -> k.startsWith(prefix)).stream() + .sorted(Comparator.comparing(ConfigurationSet::getName)) + .toList(); } /** The raw removal; existence and the tenant delete-guard are the facade's orchestration. */ diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesCvetController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesCvetController.java index 31a771569c..7802fdd37c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesCvetController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesCvetController.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.CustomVerificationEmailTemplate; import jakarta.inject.Inject; @@ -17,13 +18,13 @@ 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 org.jboss.logging.Logger; -import java.util.List; import static io.github.hectorvent.floci.services.ses.SesV2Json.parseTagsArray; import static io.github.hectorvent.floci.services.ses.SesV2Json.remapV1Exception; @@ -79,15 +80,19 @@ public class SesCvetController { @GET @Path("/custom-verification-email-templates") - public Response listCustomVerificationEmailTemplates(@Context HttpHeaders headers) { + public Response listCustomVerificationEmailTemplates(@Context HttpHeaders headers, + @QueryParam("PageSize") String pageSize, + @QueryParam("NextToken") String nextToken) { String region = regionResolver.resolveRegion(headers); + PaginatedResult page = cvetService.listCustomVerificationEmailTemplates( + region, SesListPaging.V2_LIST_CUSTOM_VERIFICATION_EMAIL_TEMPLATES, + SesListPaging.parseQueryPageSize(pageSize), nextToken); ObjectNode result = objectMapper.createObjectNode(); ArrayNode items = result.putArray("CustomVerificationEmailTemplates"); - List templates = - cvetService.listCustomVerificationEmailTemplates(region); - for (CustomVerificationEmailTemplate t : templates) { + for (CustomVerificationEmailTemplate t : page.items()) { items.add(cvetJson(t, false)); } + result.put("NextToken", page.nextToken()); return Response.ok(result).build(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesCvetService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesCvetService.java index 6b91bdf74d..f7650a537a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesCvetService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesCvetService.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.CustomVerificationEmailTemplate; @@ -72,6 +73,13 @@ public class SesCvetService { return cvetStore.get(cvetKey(region, templateName)).orElseThrow(() -> cvetNotFound(templateName)); } + public PaginatedResult listCustomVerificationEmailTemplates( + String region, SesListPaging paging, Integer pageSize, String nextToken) { + return paging.page(region, listCustomVerificationEmailTemplates(region), + CustomVerificationEmailTemplate::getTemplateName, pageSize, nextToken); + } + + /** By name; SES's own order could not be observed, since creating one needs a verified sender. */ public List listCustomVerificationEmailTemplates(String region) { String prefix = "cvet::" + region + "::"; return cvetStore.scan(k -> k.startsWith(prefix)).stream() diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobController.java index 66ad6bbf57..c4e2d1f4a7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobController.java @@ -107,10 +107,8 @@ public class SesExportJobController { String jobStatus = stringMemberOrAbsent(request, "JobStatus"); Integer pageSize = intMemberOrAbsent(request, "PageSize"); String nextToken = stringMemberOrAbsent(request, "NextToken"); - PaginatedResult page = SesListPaging.V2_LIST_EXPORT_JOBS.page( - exportJobService.listExportJobs(region, sourceType, jobStatus), - job -> SesListPaging.newestFirst(job.getCreatedTimestamp(), job.getJobId()), - pageSize, nextToken); + PaginatedResult page = exportJobService.listExportJobs(region, sourceType, jobStatus, + SesListPaging.V2_LIST_EXPORT_JOBS, pageSize, nextToken); ObjectNode result = objectMapper.createObjectNode(); ArrayNode jobs = result.putArray("ExportJobs"); diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobService.java index ec0ff33917..b69bc3132d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobService.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.RequestScopes; import io.github.hectorvent.floci.core.common.Resettable; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; @@ -26,6 +27,7 @@ import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.time.temporal.ChronoUnit; import java.util.ArrayList; +import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.Map; @@ -376,6 +378,14 @@ public class SesExportJobService implements Resettable { PRESIGNED_URL_EXPIRY_SECONDS, job.getRegion())); } + /** Floci validates the filters before the page size and token. */ + public PaginatedResult listExportJobs(String region, String sourceType, String jobStatus, + SesListPaging paging, Integer pageSize, String nextToken) { + return paging.page(region, listExportJobs(region, sourceType, jobStatus), SesExportJobService::cursor, + pageSize, nextToken); + } + + /** Newest first, as SES lists them; the paged list resumes on the same order. */ public List listExportJobs(String region, String sourceType, String jobStatus) { if (sourceType != null && !SOURCE_TYPES.contains(sourceType)) { throw new AwsException("BadRequestException", @@ -392,9 +402,14 @@ public class SesExportJobService implements Resettable { return exportJobStore.scan(k -> k.startsWith(keyPrefix(region))).stream() .filter(job -> sourceType == null || sourceType.equals(job.getExportSourceType())) .filter(job -> jobStatus == null || jobStatus.equals(job.getJobStatus())) + .sorted(Comparator.comparing(SesExportJobService::cursor)) .toList(); } + private static String cursor(ExportJob job) { + return SesListPaging.newestFirst(job.getCreatedTimestamp(), job.getJobId()); + } + public void cancelExportJob(String region, String jobId) { synchronized (createLock) { ExportJob job = getExportJob(region, jobId); diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityController.java index 9a60588b70..b8a2203f23 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityController.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.Identity; 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; @@ -121,13 +123,16 @@ public class SesIdentityController { @GET @Path("/identities") - public Response listEmailIdentities(@Context HttpHeaders headers) { + public Response listEmailIdentities(@Context HttpHeaders headers, + @QueryParam("PageSize") String pageSize, + @QueryParam("NextToken") String nextToken) { String region = regionResolver.resolveRegion(headers); - List identities = identityService.listIdentities(null, region); + PaginatedResult page = identityService.listIdentities(null, region, + SesListPaging.V2_LIST_EMAIL_IDENTITIES, SesListPaging.parseQueryPageSize(pageSize), nextToken); ObjectNode result = objectMapper.createObjectNode(); ArrayNode items = result.putArray("EmailIdentities"); - for (Identity id : identities) { + for (Identity id : page.items()) { // Only a not-yet-verified domain can still transition (via its DKIM records), // so refresh just those; refreshing every identity would scan Route53 per call. Identity current = id; @@ -145,6 +150,7 @@ public class SesIdentityController { item.put("VerificationStatus", toV2Status(current.getVerificationStatus())); items.add(item); } + result.put("NextToken", page.nextToken()); return Response.ok(result).build(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.java index 8a4b8595fa..c8de1ab065 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.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.route53.Route53Service; @@ -18,6 +19,7 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; +import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Locale; @@ -185,13 +187,23 @@ public class SesIdentityService { return id != null && "Success".equals(id.getVerificationStatus()); } + /** + * The cursor is the identity name and carries no type filter: a token taken with + * {@code IdentityType=Domain} continues the unfiltered list when reused without the filter, as + * on SES. + */ + public PaginatedResult listIdentities(String identityType, String region, SesListPaging paging, + Integer pageSize, String nextToken) { + return paging.page(region, listIdentities(identityType, region), Identity::getIdentity, pageSize, + nextToken); + } + + /** By name, the order Floci settles on where SES's own varies between calls. */ public List listIdentities(String identityType, String region) { - List all = identityStore.scan(k -> k.startsWith(keyPrefix(region))); - if (identityType == null || identityType.isBlank()) { - return all; - } - return all.stream() - .filter(i -> identityType.equals(i.getIdentityType())) + return identityStore.scan(k -> k.startsWith(keyPrefix(region))).stream() + .filter(i -> identityType == null || identityType.isBlank() + || identityType.equals(i.getIdentityType())) + .sorted(Comparator.comparing(Identity::getIdentity)) .toList(); } 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.java index 674bf3dd82..41d30d8d02 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,33 +3,65 @@ 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 io.github.hectorvent.floci.services.ses.model.EmailTemplate; import java.time.Instant; import java.util.List; import java.util.function.Function; /** - * Paging rules of the SES list operations. Probe-confirmed against real SES (2026-09-25): the - * page-size bound, both error messages and the treatment of an empty token differ per operation, - * while the token itself belongs to the kind of resource listed, so the v1 and v2 lists of the - * same resources accept each other's tokens and refuse any other list's. Without a page size the - * template lists serve 10 (probed 2026-09-26); the export-job default is not documented or - * measured and is taken to be the bound. + * Paging rules of the SES list operations. Probe-confirmed against real SES (2026-09-25 to + * 2026-09-27): the default page size, the bound, both error messages, what a v1 out-of-range + * value is served and the treatment of an empty token differ per operation, while the token itself + * belongs to the kind of resource listed, so the v1 and v2 lists of the same resources accept each + * other's tokens and refuse any other list's. A token is also bound to the region it was issued in: + * replayed in another region (probed 2026-10-01 on the identity and configuration-set lists), it + * is refused with the operation's unreadable-token error. Defaults nobody could measure are noted + * per constant. */ -enum SesListPaging { +public enum SesListPaging { V2_LIST_EMAIL_TEMPLATES(Namespace.TEMPLATE, 10, 100, size -> badRequest("The page size must be between 1 and 100"), token -> badRequest("Invalid PageToken <" + token + ">."), false), - /** v1 serves a page of the bound for an out-of-range {@code MaxItems} instead of refusing it. */ - V1_LIST_TEMPLATES(Namespace.TEMPLATE, 10, 100, - null, + V1_LIST_TEMPLATES(Namespace.TEMPLATE, 10, 100, 100, token -> invalidParameterValue("Invalid PageToken <" + token + ">."), false), + V2_LIST_EMAIL_IDENTITIES(Namespace.IDENTITY, 25, 1000, + size -> badRequest("Value " + size + " for parameter PageSize is invalid. " + + "PageSize must be between 1 and 1000."), + token -> badRequest("Invalid NextToken <" + token + ">."), + false), + + /** 195 identities came back whole without a MaxItems, so the default is taken to be the bound. */ + V1_LIST_IDENTITIES(Namespace.IDENTITY, 1000, 1000, + size -> invalidParameterValue("Value " + size + " for parameter MaxItems is invalid. " + + "MaxItems must be between 1 and 1000."), + token -> invalidParameterValue("Invalid NextToken <" + token + ">."), + false), + + V2_LIST_CONFIGURATION_SETS(Namespace.CONFIGURATION_SET, 50, 1000, + size -> badRequest("The page size must be between 1 and 1000"), + token -> badRequest("invalid nextToken " + token), + false), + + /** 1001 was served the default, so the bound is taken to be 1000; SES never refuses a value. */ + V1_LIST_CONFIGURATION_SETS(Namespace.CONFIGURATION_SET, 50, 1000, 50, + token -> new AwsException("InvalidParameterValue", null, 400), + false), + + V2_LIST_CUSTOM_VERIFICATION_EMAIL_TEMPLATES(Namespace.CUSTOM_VERIFICATION_EMAIL_TEMPLATE, 50, 50, + size -> badRequest("The page size must be between 1 and 50"), + token -> badRequest("Invalid nextToken <" + token + ">."), + false), + + V1_LIST_CUSTOM_VERIFICATION_EMAIL_TEMPLATES(Namespace.CUSTOM_VERIFICATION_EMAIL_TEMPLATE, 50, 50, 50, + token -> invalidParameterValue("Invalid nextToken <" + token + ">."), + false), + + /** AWS documents no default; it is taken to be the bound. */ V2_LIST_EXPORT_JOBS(Namespace.EXPORT_JOB, 100, 100, size -> badRequest("PageSize must be between 1 and 100"), token -> badRequest("Failed to deserialize token. "), @@ -37,6 +69,9 @@ enum SesListPaging { private static final class Namespace { static final String TEMPLATE = "template"; + static final String IDENTITY = "identity"; + static final String CONFIGURATION_SET = "configuration-set"; + static final String CUSTOM_VERIFICATION_EMAIL_TEMPLATE = "custom-verification-email-template"; static final String EXPORT_JOB = "export-job"; } @@ -44,27 +79,41 @@ enum SesListPaging { private final int defaultPageSize; private final int maxPageSize; private final Function outOfRange; + private final int servedWhenOutOfRange; private final Function invalidToken; private final boolean emptyTokenInvalid; SesListPaging(String namespace, int defaultPageSize, int maxPageSize, Function outOfRange, Function invalidToken, boolean emptyTokenInvalid) { + this(namespace, defaultPageSize, maxPageSize, outOfRange, 0, invalidToken, emptyTokenInvalid); + } + + SesListPaging(String namespace, int defaultPageSize, int maxPageSize, int servedWhenOutOfRange, + Function invalidToken, boolean emptyTokenInvalid) { + this(namespace, defaultPageSize, maxPageSize, null, servedWhenOutOfRange, invalidToken, + emptyTokenInvalid); + } + + SesListPaging(String namespace, int defaultPageSize, int maxPageSize, + Function outOfRange, int servedWhenOutOfRange, + Function invalidToken, boolean emptyTokenInvalid) { this.namespace = namespace; this.defaultPageSize = defaultPageSize; this.maxPageSize = maxPageSize; this.outOfRange = outOfRange; + this.servedWhenOutOfRange = servedWhenOutOfRange; this.invalidToken = invalidToken; this.emptyTokenInvalid = emptyTokenInvalid; } - PaginatedResult page(List all, Function cursorOf, Integer pageSize, + PaginatedResult page(String region, List all, Function cursorOf, Integer pageSize, String nextToken) { int limit = pageSize(pageSize); if (nextToken != null && nextToken.isEmpty() && emptyTokenInvalid) { throw invalidToken.apply(nextToken); } - return Pagination.paginate(all, cursorOf, limit, nextToken, namespace, invalidToken); + return Pagination.paginate(all, cursorOf, limit, nextToken, namespace + "@" + region, invalidToken); } int pageSize(Integer requested) { @@ -73,7 +122,7 @@ enum SesListPaging { } if (requested < 1 || requested > maxPageSize) { if (outOfRange == null) { - return maxPageSize; + return servedWhenOutOfRange; } throw outOfRange.apply(requested); } @@ -86,10 +135,6 @@ enum SesListPaging { return descending + "#" + id; } - static String templateCursor(EmailTemplate template) { - return newestFirst(template.getCreatedTimestamp(), template.getTemplateName()); - } - /** 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.java index ea5b9bf2e9..63c09050c2 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 @@ -127,7 +127,7 @@ public class SesQueryHandler { case "GetCustomVerificationEmailTemplate" -> handleGetCustomVerificationEmailTemplate(params, region); case "ListCustomVerificationEmailTemplates" -> - handleListCustomVerificationEmailTemplates(region); + handleListCustomVerificationEmailTemplates(params, region); case "UpdateCustomVerificationEmailTemplate" -> handleUpdateCustomVerificationEmailTemplate(params, region); case "DeleteCustomVerificationEmailTemplate" -> @@ -136,7 +136,7 @@ public class SesQueryHandler { handleSendCustomVerificationEmail(params, region); case "CreateConfigurationSet" -> handleCreateConfigurationSet(params, region); case "DescribeConfigurationSet" -> handleDescribeConfigurationSet(params, region); - case "ListConfigurationSets" -> handleListConfigurationSets(region); + case "ListConfigurationSets" -> handleListConfigurationSets(params, region); case "DeleteConfigurationSet" -> handleDeleteConfigurationSet(params, region); case "CreateConfigurationSetEventDestination" -> handleCreateConfigurationSetEventDestination(params, region); @@ -207,13 +207,17 @@ public class SesQueryHandler { private Response handleListIdentities(MultivaluedMap params, String region) { String identityType = getParam(params, "IdentityType"); - List identities = identityService.listIdentities(identityType, region); + PaginatedResult page = identityService.listIdentities(identityType, region, + SesListPaging.V1_LIST_IDENTITIES, + SesListPaging.parseQueryProtocolPageSize(getParam(params, "MaxItems")), + getParam(params, "NextToken")); - var xml = new XmlBuilder().start("Identities"); - for (Identity id : identities) { + XmlBuilder xml = new XmlBuilder().start("Identities"); + for (Identity id : page.items()) { xml.elem("member", id.getIdentity()); } xml.end("Identities"); + xml.elem("NextToken", page.nextToken()); return Response.ok(AwsQueryResponse.envelope("ListIdentities", AwsNamespaces.SES, xml.build())).build(); } @@ -587,8 +591,8 @@ public class SesQueryHandler { } private Response handleListTemplates(MultivaluedMap params, String region) { - PaginatedResult page = SesListPaging.V1_LIST_TEMPLATES.page( - templateService.listTemplates(region), SesListPaging::templateCursor, + PaginatedResult page = templateService.listTemplates(region, + SesListPaging.V1_LIST_TEMPLATES, SesListPaging.parseQueryProtocolPageSize(getParam(params, "MaxItems")), getParam(params, "NextToken")); XmlBuilder xml = new XmlBuilder().start("TemplatesMetadata"); @@ -691,11 +695,14 @@ public class SesQueryHandler { "GetCustomVerificationEmailTemplate", AwsNamespaces.SES, xml)).build(); } - private Response handleListCustomVerificationEmailTemplates(String region) { + private Response handleListCustomVerificationEmailTemplates(MultivaluedMap params, + String region) { + PaginatedResult page = cvetService.listCustomVerificationEmailTemplates( + region, SesListPaging.V1_LIST_CUSTOM_VERIFICATION_EMAIL_TEMPLATES, + SesListPaging.parseQueryProtocolPageSize(getParam(params, "MaxResults")), + getParam(params, "NextToken")); XmlBuilder xml = new XmlBuilder().start("CustomVerificationEmailTemplates"); - List templates = - cvetService.listCustomVerificationEmailTemplates(region); - for (CustomVerificationEmailTemplate t : templates) { + for (CustomVerificationEmailTemplate t : page.items()) { xml.start("member") .elem("TemplateName", t.getTemplateName()) .elem("FromEmailAddress", t.getFromEmailAddress()) @@ -705,6 +712,7 @@ public class SesQueryHandler { .end("member"); } xml.end("CustomVerificationEmailTemplates"); + xml.elem("NextToken", page.nextToken()); return Response.ok(AwsQueryResponse.envelope( "ListCustomVerificationEmailTemplates", AwsNamespaces.SES, xml.build())).build(); } @@ -928,13 +936,17 @@ public class SesQueryHandler { } } - private Response handleListConfigurationSets(String region) { - List all = configSetService.list(region); + private Response handleListConfigurationSets(MultivaluedMap params, String region) { + PaginatedResult page = configSetService.list(region, + SesListPaging.V1_LIST_CONFIGURATION_SETS, + SesListPaging.parseQueryProtocolPageSize(getParam(params, "MaxItems")), + getParam(params, "NextToken")); XmlBuilder xml = new XmlBuilder().start("ConfigurationSets"); - for (ConfigurationSet cs : all) { + for (ConfigurationSet cs : page.items()) { xml.start("member").elem("Name", cs.getName()).end("member"); } xml.end("ConfigurationSets"); + xml.elem("NextToken", page.nextToken()); return Response.ok(AwsQueryResponse.envelope("ListConfigurationSets", AwsNamespaces.SES, xml.build())).build(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateController.java index 0b61f4f269..ff0757d329 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateController.java @@ -91,9 +91,8 @@ public class SesTemplateController { @QueryParam("PageSize") String pageSize, @QueryParam("NextToken") String nextToken) { String region = regionResolver.resolveRegion(headers); - PaginatedResult page = SesListPaging.V2_LIST_EMAIL_TEMPLATES.page( - templateService.listTemplates(region), SesListPaging::templateCursor, - SesListPaging.parseQueryPageSize(pageSize), nextToken); + PaginatedResult page = templateService.listTemplates(region, + SesListPaging.V2_LIST_EMAIL_TEMPLATES, SesListPaging.parseQueryPageSize(pageSize), nextToken); ObjectNode result = objectMapper.createObjectNode(); ArrayNode items = result.putArray("TemplatesMetadata"); for (EmailTemplate t : page.items()) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateService.java index f53bc6249c..8580b704d1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateService.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; 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.EmailContent; @@ -20,6 +21,7 @@ import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; +import java.util.Comparator; import java.util.HashSet; import java.util.HexFormat; import java.util.List; @@ -123,9 +125,21 @@ public class SesTemplateService { LOG.infov("Deleted SES template: {0} in region {1}", templateName, region); } + public PaginatedResult listTemplates(String region, SesListPaging paging, Integer pageSize, + String nextToken) { + return paging.page(region, listTemplates(region), SesTemplateService::cursor, pageSize, nextToken); + } + + /** Newest first, as SES lists them; the paged lists resume on the same order. */ public List listTemplates(String region) { String prefix = "template::" + region + "::"; - return templateStore.scan(k -> k.startsWith(prefix)); + return templateStore.scan(k -> k.startsWith(prefix)).stream() + .sorted(Comparator.comparing(SesTemplateService::cursor)) + .toList(); + } + + private static String cursor(EmailTemplate template) { + return SesListPaging.newestFirst(template.getCreatedTimestamp(), template.getTemplateName()); } /** diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetPagingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetPagingIntegrationTest.java new file mode 100644 index 0000000000..ae5c0fc0da --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetPagingIntegrationTest.java @@ -0,0 +1,147 @@ +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 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.equalTo; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; + +/** + * Paging of the v1 and v2 {@code ListConfigurationSets} lists, which share one token namespace. + * Runs in its own region so the configuration sets created here are the whole list. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesConfigurationSetPagingIntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-west-1/ses/aws4_request"; + private static final String V1_ROOT = "ListConfigurationSetsResponse.ListConfigurationSetsResult."; + + @Test + @Order(1) + void createConfigurationSetsOutOfNameOrder() { + for (String name : new String[] {"page-b", "page-c", "page-a"}) { + create(name); + } + } + + @Test + @Order(2) + void v2_walksByNameAndEndsOnANullToken() { + String token = given().header("Authorization", AUTH).queryParam("PageSize", 1) + .when().get("/v2/email/configuration-sets").then().statusCode(200) + .body("ConfigurationSets", contains("page-a")) + .body("NextToken", notNullValue()) + .extract().path("NextToken"); + + given().header("Authorization", AUTH).queryParam("PageSize", 2).queryParam("NextToken", token) + .when().get("/v2/email/configuration-sets").then().statusCode(200) + .body("ConfigurationSets", contains("page-b", "page-c")) + .body("$", hasKey("NextToken")) + .body("NextToken", nullValue()); + } + + @Test + @Order(3) + void v1_walksByNameAndOmitsTheTokenOnTheLastPage() { + XmlPath first = listV1("1", null); + assertThat(first.getList(V1_ROOT + "ConfigurationSets.member.Name"), contains("page-a")); + + given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", "ListConfigurationSets").formParam("MaxItems", "2") + .formParam("NextToken", first.getString(V1_ROOT + "NextToken")) + .when().post("/").then().statusCode(200) + .body(containsString("page-c")) + .body(not(containsString(""))); + } + + @Test + @Order(4) + void tokensCarryOverBetweenV1AndV2() { + String v1Token = listV1("1", null).getString(V1_ROOT + "NextToken"); + given().header("Authorization", AUTH).queryParam("NextToken", v1Token) + .when().get("/v2/email/configuration-sets").then().statusCode(200) + .body("ConfigurationSets", contains("page-b", "page-c")); + + String v2Token = given().header("Authorization", AUTH).queryParam("PageSize", 1) + .when().get("/v2/email/configuration-sets").then().statusCode(200) + .extract().path("NextToken"); + assertThat(listV1(null, v2Token).getList(V1_ROOT + "ConfigurationSets.member.Name"), + contains("page-b", "page-c")); + } + + @Test + @Order(5) + void outOfRangeSizesAndUnreadableTokensFollowEachApi() { + given().header("Authorization", AUTH).queryParam("PageSize", 0) + .when().get("/v2/email/configuration-sets").then().statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo("The page size must be between 1 and 1000")); + given().header("Authorization", AUTH).queryParam("NextToken", "garbage") + .when().get("/v2/email/configuration-sets").then().statusCode(400) + .body("message", equalTo("invalid nextToken garbage")); + + // v1 serves an out-of-range MaxItems rather than refusing it, and names no reason for a + // token it cannot read. + assertThat(listV1("0", null).getList(V1_ROOT + "ConfigurationSets.member.Name"), + contains("page-a", "page-b", "page-c")); + given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", "ListConfigurationSets").formParam("NextToken", "garbage") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(not(containsString(""))); + } + + @Test + @Order(6) + void withoutAPageSizeOrOutOfRangeBothApisServeFifty() { + for (int i = 0; i < 48; i++) { + create("more-%02d".formatted(i)); + } + + given().header("Authorization", AUTH) + .when().get("/v2/email/configuration-sets").then().statusCode(200) + .body("ConfigurationSets", hasSize(50)) + .body("NextToken", notNullValue()); + + for (String maxItems : new String[] {null, "0", "1001"}) { + XmlPath v1 = listV1(maxItems, null); + assertThat(v1.getList(V1_ROOT + "ConfigurationSets.member.Name"), hasSize(50)); + assertThat(v1.getString(V1_ROOT + "NextToken"), not(emptyOrNullString())); + } + } + + private static void create(String name) { + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"ConfigurationSetName\": \"" + name + "\"}") + .when().post("/v2/email/configuration-sets").then().statusCode(200); + } + + private static XmlPath listV1(String maxItems, String nextToken) { + RequestSpecification request = given() + .contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", "ListConfigurationSets"); + if (maxItems != null) { + request.formParam("MaxItems", maxItems); + } + if (nextToken != null) { + request.formParam("NextToken", nextToken); + } + return request.when().post("/").then().statusCode(200).extract().xmlPath(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetServiceTest.java index c9e6c84d5e..7e5c2a8088 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetServiceTest.java @@ -62,18 +62,16 @@ class SesConfigurationSetServiceTest { } @Test - void list_isPerRegion_sortedByCreation() { + void list_isPerRegion_sortedByName() { service.create(cs("b-cs"), REGION); service.create(cs("a-cs"), REGION); service.create(cs("other"), "eu-west-1"); - // create() stamps Instant.now(), which can collide within one clock tick and fall back to - // the name tie-break; pin distinct timestamps through the escape hatch so the - // creation-order assertion stays deterministic. + // Creation time no longer decides the order, so pin b-cs as the older one and expect the + // name order regardless. stampCreated("b-cs", Instant.parse("2026-01-01T00:00:00Z")); stampCreated("a-cs", Instant.parse("2026-01-02T00:00:00Z")); List list = service.list(REGION); - assertEquals(2, list.size()); - assertEquals("b-cs", list.get(0).getName()); + assertEquals(List.of("a-cs", "b-cs"), list.stream().map(ConfigurationSet::getName).toList()); } private void stampCreated(String name, Instant timestamp) { diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesCustomVerificationEmailTemplatePagingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesCustomVerificationEmailTemplatePagingIntegrationTest.java new file mode 100644 index 0000000000..c994629653 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesCustomVerificationEmailTemplatePagingIntegrationTest.java @@ -0,0 +1,161 @@ +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 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.equalTo; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; + +/** + * Paging of the v1 and v2 {@code ListCustomVerificationEmailTemplates} lists, which share one token + * namespace. Runs in its own region so the templates created here are the whole list. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesCustomVerificationEmailTemplatePagingIntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/eu-south-1/ses/aws4_request"; + private static final String BASE = "/v2/email/custom-verification-email-templates"; + private static final String FROM = "cvet-page-sender@floci.test"; + private static final String V1_ROOT = + "ListCustomVerificationEmailTemplatesResponse.ListCustomVerificationEmailTemplatesResult."; + + @Test + @Order(1) + void createTemplatesOutOfNameOrder() { + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"EmailIdentity\": \"" + FROM + "\"}") + .when().post("/v2/email/identities").then().statusCode(200); + for (String name : new String[] {"page-b", "page-c", "page-a"}) { + create(name); + } + } + + @Test + @Order(2) + void v2_walksByNameAndEndsOnANullToken() { + String token = given().header("Authorization", AUTH).queryParam("PageSize", 1) + .when().get(BASE).then().statusCode(200) + .body("CustomVerificationEmailTemplates.TemplateName", contains("page-a")) + .body("NextToken", notNullValue()) + .extract().path("NextToken"); + + given().header("Authorization", AUTH).queryParam("PageSize", 2).queryParam("NextToken", token) + .when().get(BASE).then().statusCode(200) + .body("CustomVerificationEmailTemplates.TemplateName", contains("page-b", "page-c")) + .body("$", hasKey("NextToken")) + .body("NextToken", nullValue()); + } + + @Test + @Order(3) + void v1_walksByNameAndOmitsTheTokenOnTheLastPage() { + XmlPath first = listV1("1", null); + assertThat(first.getList(V1_ROOT + "CustomVerificationEmailTemplates.member.TemplateName"), + contains("page-a")); + + given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", "ListCustomVerificationEmailTemplates").formParam("MaxResults", "2") + .formParam("NextToken", first.getString(V1_ROOT + "NextToken")) + .when().post("/").then().statusCode(200) + .body(containsString("page-c")) + .body(not(containsString(""))); + } + + @Test + @Order(4) + void tokensCarryOverBetweenV1AndV2() { + String v1Token = listV1("1", null).getString(V1_ROOT + "NextToken"); + given().header("Authorization", AUTH).queryParam("NextToken", v1Token) + .when().get(BASE).then().statusCode(200) + .body("CustomVerificationEmailTemplates.TemplateName", contains("page-b", "page-c")); + + String v2Token = given().header("Authorization", AUTH).queryParam("PageSize", 1) + .when().get(BASE).then().statusCode(200) + .extract().path("NextToken"); + assertThat(listV1(null, v2Token).getList(V1_ROOT + "CustomVerificationEmailTemplates.member.TemplateName"), + contains("page-b", "page-c")); + } + + @Test + @Order(5) + void outOfRangeSizesAndUnreadableTokensFollowEachApi() { + given().header("Authorization", AUTH).queryParam("PageSize", 51) + .when().get(BASE).then().statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo("The page size must be between 1 and 50")); + given().header("Authorization", AUTH).queryParam("NextToken", "garbage") + .when().get(BASE).then().statusCode(400) + .body("message", equalTo("Invalid nextToken .")); + + assertThat(listV1("0", null).getList(V1_ROOT + "CustomVerificationEmailTemplates.member.TemplateName"), + contains("page-a", "page-b", "page-c")); + given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", "ListCustomVerificationEmailTemplates").formParam("NextToken", "garbage") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("Invalid nextToken <garbage>.")); + } + + @Test + @Order(6) + void withoutAPageSizeOrOutOfRangeBothApisServeFifty() { + for (int i = 0; i < 48; i++) { + create("more-%02d".formatted(i)); + } + + given().header("Authorization", AUTH) + .when().get(BASE).then().statusCode(200) + .body("CustomVerificationEmailTemplates", hasSize(50)) + .body("NextToken", notNullValue()); + + for (String maxResults : new String[] {null, "0", "51"}) { + XmlPath v1 = listV1(maxResults, null); + assertThat(v1.getList(V1_ROOT + "CustomVerificationEmailTemplates.member"), hasSize(50)); + assertThat(v1.getString(V1_ROOT + "NextToken"), not(emptyOrNullString())); + } + } + + private static void create(String name) { + given().contentType("application/json").header("Authorization", AUTH) + .body(""" + { + "TemplateName": "%s", + "FromEmailAddress": "%s", + "TemplateSubject": "Verify", + "TemplateContent": "verify", + "SuccessRedirectionURL": "https://example.com/ok", + "FailureRedirectionURL": "https://example.com/fail" + } + """.formatted(name, FROM)) + .when().post(BASE).then().statusCode(200); + } + + private static XmlPath listV1(String maxResults, String nextToken) { + RequestSpecification request = given() + .contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", "ListCustomVerificationEmailTemplates"); + if (maxResults != null) { + request.formParam("MaxResults", maxResults); + } + if (nextToken != null) { + request.formParam("NextToken", nextToken); + } + return request.when().post("/").then().statusCode(200).extract().xmlPath(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityPagingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityPagingIntegrationTest.java new file mode 100644 index 0000000000..3423247d74 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityPagingIntegrationTest.java @@ -0,0 +1,179 @@ +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 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.equalTo; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; + +/** + * Paging of the v1 {@code ListIdentities} and v2 {@code ListEmailIdentities} lists, which share one + * token namespace. Runs in its own region so the identities created here are the whole list. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesIdentityPagingIntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/ap-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 V1_ROOT = "ListIdentitiesResponse.ListIdentitiesResult."; + + @Test + @Order(1) + void createIdentitiesOutOfNameOrder() { + for (String identity : new String[] {"page-b.test", "zz@page.test", "page-c.test", "page-a.test"}) { + create(identity); + } + } + + @Test + @Order(2) + void v2_walksByNameAndEndsOnANullToken() { + String token = given().header("Authorization", AUTH).queryParam("PageSize", 1) + .when().get("/v2/email/identities").then().statusCode(200) + .body("EmailIdentities.IdentityName", contains("page-a.test")) + .body("NextToken", notNullValue()) + .extract().path("NextToken"); + + given().header("Authorization", AUTH).queryParam("PageSize", 3).queryParam("NextToken", token) + .when().get("/v2/email/identities").then().statusCode(200) + .body("EmailIdentities.IdentityName", contains("page-b.test", "page-c.test", "zz@page.test")) + .body("$", hasKey("NextToken")) + .body("NextToken", nullValue()); + } + + @Test + @Order(3) + void v1_walksByNameAndOmitsTheTokenOnTheLastPage() { + XmlPath first = listV1("1", null, null); + assertThat(first.getList(V1_ROOT + "Identities.member"), contains("page-a.test")); + + given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", "ListIdentities").formParam("MaxItems", "3") + .formParam("NextToken", first.getString(V1_ROOT + "NextToken")) + .when().post("/").then().statusCode(200) + .body(containsString("zz@page.test")) + .body(not(containsString(""))); + } + + @Test + @Order(4) + void v1_aTokenTakenWithATypeFilterContinuesAListWithoutIt() { + String token = listV1("1", null, "Domain").getString(V1_ROOT + "NextToken"); + + assertThat(listV1(null, token, null).getList(V1_ROOT + "Identities.member"), + contains("page-b.test", "page-c.test", "zz@page.test")); + } + + @Test + @Order(5) + void tokensCarryOverBetweenV1AndV2() { + String v1Token = listV1("1", null, null).getString(V1_ROOT + "NextToken"); + given().header("Authorization", AUTH).queryParam("NextToken", v1Token) + .when().get("/v2/email/identities").then().statusCode(200) + .body("EmailIdentities.IdentityName", contains("page-b.test", "page-c.test", "zz@page.test")); + + String v2Token = given().header("Authorization", AUTH).queryParam("PageSize", 1) + .when().get("/v2/email/identities").then().statusCode(200) + .extract().path("NextToken"); + assertThat(listV1(null, v2Token, null).getList(V1_ROOT + "Identities.member"), + contains("page-b.test", "page-c.test", "zz@page.test")); + } + + @Test + @Order(6) + void outOfRangeSizesAndUnreadableTokensAreRefused() { + given().header("Authorization", AUTH).queryParam("PageSize", 1001) + .when().get("/v2/email/identities").then().statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo( + "Value 1001 for parameter PageSize is invalid. PageSize must be between 1 and 1000.")); + given().header("Authorization", AUTH).queryParam("NextToken", "garbage") + .when().get("/v2/email/identities").then().statusCode(400) + .body("message", equalTo("Invalid NextToken .")); + + given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", "ListIdentities").formParam("MaxItems", "0") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString( + "Value 0 for parameter MaxItems is invalid. MaxItems must be between 1 and 1000.")); + given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", "ListIdentities").formParam("NextToken", "garbage") + .when().post("/").then().statusCode(400) + .body(containsString("Invalid NextToken <garbage>.")); + } + + @Test + @Order(7) + void aTokenIsRefusedInAnotherRegion() { + String token = given().header("Authorization", AUTH).queryParam("PageSize", 1) + .when().get("/v2/email/identities").then().statusCode(200) + .extract().path("NextToken"); + + given().header("Authorization", OTHER_REGION_AUTH).queryParam("NextToken", token) + .when().get("/v2/email/identities").then().statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo("Invalid NextToken <" + token + ">.")); + given().contentType("application/x-www-form-urlencoded").header("Authorization", OTHER_REGION_AUTH) + .formParam("Action", "ListIdentities").formParam("NextToken", token) + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("Invalid NextToken <" + token + ">.")); + } + + @Test + @Order(8) + void withoutAPageSizeV2ServesTwentyFiveAndV1ServesEverything() { + for (int i = 0; i < 22; i++) { + create("more-%02d.test".formatted(i)); + } + + given().header("Authorization", AUTH) + .when().get("/v2/email/identities").then().statusCode(200) + .body("EmailIdentities", hasSize(25)) + .body("NextToken", notNullValue()); + + XmlPath v1 = listV1(null, null, null); + assertThat(v1.getList(V1_ROOT + "Identities.member"), hasSize(26)); + assertThat(v1.getString(V1_ROOT + "NextToken"), emptyOrNullString()); + } + + private static void create(String identity) { + given().contentType("application/json").header("Authorization", AUTH) + .body("{\"EmailIdentity\": \"" + identity + "\"}") + .when().post("/v2/email/identities").then().statusCode(200); + } + + private static XmlPath listV1(String maxItems, String nextToken, String identityType) { + RequestSpecification request = given() + .contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", "ListIdentities"); + if (maxItems != null) { + request.formParam("MaxItems", maxItems); + } + if (nextToken != null) { + request.formParam("NextToken", nextToken); + } + if (identityType != null) { + request.formParam("IdentityType", identityType); + } + return request.when().post("/").then().statusCode(200).extract().xmlPath(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityServiceTest.java index 2504dc0dbc..14f3a13faf 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityServiceTest.java @@ -75,7 +75,8 @@ class SesIdentityServiceTest { service.verifyEmailIdentity("alice@example.com", REGION); service.save(new Identity("example.com", "Domain"), REGION); service.verifyEmailIdentity("other@example.com", "eu-west-1"); - assertEquals(2, service.listIdentities(null, REGION).size()); + assertEquals(List.of("alice@example.com", "example.com"), + service.listIdentities(null, REGION).stream().map(Identity::getIdentity).toList()); assertEquals(List.of("example.com"), service.listIdentities("Domain", REGION).stream().map(Identity::getIdentity).toList()); } 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.java index 78bd5d498d..67289871e5 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 @@ -17,6 +17,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; class SesListPagingTest { + private static final String REGION = "us-east-1"; private static final List ITEMS = List.of("a", "b", "c"); @Test @@ -43,6 +44,70 @@ class SesListPagingTest { } } + @Test + void pageSize_sharedResourceDefaultsFollowTheProbe() { + assertEquals(25, SesListPaging.V2_LIST_EMAIL_IDENTITIES.pageSize(null)); + assertEquals(1000, SesListPaging.V1_LIST_IDENTITIES.pageSize(null)); + assertEquals(50, SesListPaging.V2_LIST_CONFIGURATION_SETS.pageSize(null)); + assertEquals(50, SesListPaging.V1_LIST_CONFIGURATION_SETS.pageSize(null)); + assertEquals(50, SesListPaging.V2_LIST_CUSTOM_VERIFICATION_EMAIL_TEMPLATES.pageSize(null)); + assertEquals(50, SesListPaging.V1_LIST_CUSTOM_VERIFICATION_EMAIL_TEMPLATES.pageSize(null)); + } + + @Test + void pageSize_v1ConfigurationSetsAndCvetsServeFiftyForAnOutOfRangeValue() { + for (int size : new int[] {0, -1, 1001, Integer.MAX_VALUE}) { + assertEquals(50, SesListPaging.V1_LIST_CONFIGURATION_SETS.pageSize(size)); + assertEquals(50, SesListPaging.V1_LIST_CUSTOM_VERIFICATION_EMAIL_TEMPLATES.pageSize(size)); + } + } + + @Test + void pageSize_sharedResourceOutOfRangeMessages() { + assertError("BadRequestException", + "Value 1001 for parameter PageSize is invalid. PageSize must be between 1 and 1000.", + () -> SesListPaging.V2_LIST_EMAIL_IDENTITIES.pageSize(1001)); + assertError("InvalidParameterValue", + "Value 0 for parameter MaxItems is invalid. MaxItems must be between 1 and 1000.", + () -> SesListPaging.V1_LIST_IDENTITIES.pageSize(0)); + assertError("BadRequestException", "The page size must be between 1 and 1000", + () -> SesListPaging.V2_LIST_CONFIGURATION_SETS.pageSize(0)); + assertError("BadRequestException", "The page size must be between 1 and 50", + () -> SesListPaging.V2_LIST_CUSTOM_VERIFICATION_EMAIL_TEMPLATES.pageSize(51)); + } + + @Test + void sharedResourceTokens_crossBetweenV1AndV2ButNotBetweenKinds() { + String identityToken = page(SesListPaging.V1_LIST_IDENTITIES, 1, null).nextToken(); + assertThat(page(SesListPaging.V2_LIST_EMAIL_IDENTITIES, 1, identityToken).items(), contains("b")); + + String configSetToken = page(SesListPaging.V2_LIST_CONFIGURATION_SETS, 1, null).nextToken(); + assertThat(page(SesListPaging.V1_LIST_CONFIGURATION_SETS, 1, configSetToken).items(), contains("b")); + + String cvetToken = page(SesListPaging.V2_LIST_CUSTOM_VERIFICATION_EMAIL_TEMPLATES, 1, null).nextToken(); + assertThat(page(SesListPaging.V1_LIST_CUSTOM_VERIFICATION_EMAIL_TEMPLATES, 1, cvetToken).items(), + contains("b")); + + assertError("BadRequestException", "invalid nextToken " + identityToken, + () -> page(SesListPaging.V2_LIST_CONFIGURATION_SETS, 1, identityToken)); + assertError("InvalidParameterValue", null, + () -> page(SesListPaging.V1_LIST_CONFIGURATION_SETS, 1, identityToken)); + } + + @Test + void invalidToken_sharedResourceMessages() { + assertError("BadRequestException", "Invalid NextToken .", + () -> page(SesListPaging.V2_LIST_EMAIL_IDENTITIES, 1, "garbage")); + assertError("InvalidParameterValue", "Invalid NextToken .", + () -> page(SesListPaging.V1_LIST_IDENTITIES, 1, "garbage")); + assertError("BadRequestException", "invalid nextToken garbage", + () -> page(SesListPaging.V2_LIST_CONFIGURATION_SETS, 1, "garbage")); + assertError("BadRequestException", "Invalid nextToken .", + () -> page(SesListPaging.V2_LIST_CUSTOM_VERIFICATION_EMAIL_TEMPLATES, 1, "garbage")); + assertError("InvalidParameterValue", "Invalid nextToken .", + () -> page(SesListPaging.V1_LIST_CUSTOM_VERIFICATION_EMAIL_TEMPLATES, 1, "garbage")); + } + @Test void templateTokens_areSharedBetweenV1AndV2AndRefusedByExportJobs() { String v1Token = page(SesListPaging.V1_LIST_TEMPLATES, 1, null).nextToken(); @@ -52,6 +117,17 @@ class SesListPagingTest { () -> page(SesListPaging.V2_LIST_EXPORT_JOBS, 1, v1Token)); } + @Test + void aTokenFromAnotherRegion_isRefusedAsUnreadable() { + String token = page(SesListPaging.V2_LIST_EMAIL_IDENTITIES, 1, null).nextToken(); + + assertError("BadRequestException", "Invalid NextToken <" + token + ">.", + () -> SesListPaging.V2_LIST_EMAIL_IDENTITIES.page("us-west-2", ITEMS, Function.identity(), 1, token)); + assertError("InvalidParameterValue", "Invalid NextToken <" + token + ">.", + () -> SesListPaging.V1_LIST_IDENTITIES.page("us-west-2", ITEMS, Function.identity(), 1, token)); + assertThat(page(SesListPaging.V1_LIST_IDENTITIES, 1, token).items(), contains("b")); + } + @Test void invalidToken_messagesQuoteTheToken() { assertError("BadRequestException", "Invalid PageToken .", @@ -110,13 +186,13 @@ class SesListPagingTest { @Test void pageSize_isReportedBeforeTheToken() { assertError("BadRequestException", "PageSize must be between 1 and 100", - () -> SesListPaging.V2_LIST_EXPORT_JOBS.page(ITEMS, Function.identity(), 0, "")); + () -> SesListPaging.V2_LIST_EXPORT_JOBS.page(REGION, ITEMS, Function.identity(), 0, "")); assertError("BadRequestException", "The page size must be between 1 and 100", - () -> SesListPaging.V2_LIST_EMAIL_TEMPLATES.page(ITEMS, Function.identity(), 0, "garbage")); + () -> SesListPaging.V2_LIST_EMAIL_TEMPLATES.page(REGION, ITEMS, Function.identity(), 0, "garbage")); } private static PaginatedResult page(SesListPaging paging, int size, String token) { - return paging.page(ITEMS, Function.identity(), size, token); + return paging.page(REGION, ITEMS, Function.identity(), size, token); } private static void assertError(String code, String message, Runnable call) { diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesTemplateServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesTemplateServiceTest.java index 19dfe79f3f..656c3e3e3a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesTemplateServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesTemplateServiceTest.java @@ -20,8 +20,6 @@ import java.time.Instant; import java.util.List; import java.util.stream.Stream; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -117,14 +115,17 @@ class SesTemplateServiceTest { } @Test - void list_isPerRegion() { - service.createTemplate(template("a"), REGION); - service.createTemplate(template("b"), REGION); - service.createTemplate(template("other"), "eu-west-1"); + void list_isPerRegion_newestFirst() { + SesTemplateService ticking = new SesTemplateService(new InMemoryStorage<>(), new ObjectMapper(), + new SecureRandom(), new MutableClock()); + for (String name : List.of("a", "b", "c", "d", "e")) { + ticking.createTemplate(template(name), REGION); + } + ticking.createTemplate(template("other"), "eu-west-1"); - List names = service.listTemplates(REGION).stream() + List names = ticking.listTemplates(REGION).stream() .map(EmailTemplate::getTemplateName).toList(); - assertThat(names, containsInAnyOrder("a", "b")); + assertEquals(List.of("e", "d", "c", "b", "a"), names); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2IntegrationTest.java index 56bc8f0ff5..c8ced21498 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesV2IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2IntegrationTest.java @@ -86,9 +86,11 @@ class SesV2IntegrationTest { @Test @Order(4) void listEmailIdentities() { + // Other classes share this region, so ask for a page large enough to hold every identity. given() .contentType("application/json") .header("Authorization", AUTH_HEADER) + .queryParam("PageSize", 1000) .when() .get("/v2/email/identities") .then()