Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(ses): paginate template lists and align ListExportJobs paging (#4465)

Kenshin Okinaka3441532a9dec
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTemplatePagingTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTemplatePagingTest.java
new file mode 100644
index 0000000000..7c78fdcdc0
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTemplatePagingTest.java
@@ -0,0 +1,108 @@
+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.ListTemplatesRequest;
+import software.amazon.awssdk.services.ses.model.ListTemplatesResponse;
+import software.amazon.awssdk.services.ses.model.TemplateMetadata;
+import software.amazon.awssdk.services.sesv2.SesV2Client;
+import software.amazon.awssdk.services.sesv2.model.CreateEmailTemplateRequest;
+import software.amazon.awssdk.services.sesv2.model.DeleteEmailTemplateRequest;
+import software.amazon.awssdk.services.sesv2.model.EmailTemplateContent;
+import software.amazon.awssdk.services.sesv2.model.EmailTemplateMetadata;
+import software.amazon.awssdk.services.sesv2.model.ListEmailTemplatesRequest;
+import software.amazon.awssdk.services.sesv2.model.ListEmailTemplatesResponse;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+@DisplayName("SES template list paging")
+class SesTemplatePagingTest {
+
+ private static SesClient sesV1;
+ private static SesV2Client sesV2;
+ private static List<String> 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.createEmailTemplate(CreateEmailTemplateRequest.builder()
+ .templateName(name)
+ .templateContent(EmailTemplateContent.builder().subject("s").text("t").build())
+ .build());
+ }
+ }
+
+ @AfterAll
+ static void cleanup() {
+ if (sesV2 != null) {
+ for (String name : names) {
+ try {
+ sesV2.deleteEmailTemplate(DeleteEmailTemplateRequest.builder()
+ .templateName(name).build());
+ } catch (Exception ignored) {
+ // Best-effort cleanup; a leftover template 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<String> listed = new ArrayList<>();
+ for (ListEmailTemplatesResponse page : sesV2.listEmailTemplatesPaginator(
+ ListEmailTemplatesRequest.builder().pageSize(1).build())) {
+ assertThat(page.templatesMetadata()).hasSizeLessThanOrEqualTo(1);
+ page.templatesMetadata().forEach(meta -> listed.add(meta.templateName()));
+ }
+
+ assertThat(listed).doesNotHaveDuplicates();
+ assertThat(listed.stream().filter(names::contains)).containsExactlyInAnyOrderElementsOf(names);
+ }
+
+ @Test
+ @DisplayName("V1 MaxItems pages over every template once and ends without a token")
+ void v1PagesOverEveryTemplateOnce() {
+ List<String> listed = new ArrayList<>();
+ String token = null;
+ do {
+ ListTemplatesResponse page = sesV1.listTemplates(ListTemplatesRequest.builder()
+ .maxItems(1).nextToken(token).build());
+ assertThat(page.templatesMetadata()).hasSizeLessThanOrEqualTo(1);
+ page.templatesMetadata().stream().map(TemplateMetadata::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() {
+ ListTemplatesResponse first = sesV1.listTemplates(ListTemplatesRequest.builder()
+ .maxItems(1).build());
+ assertThat(first.nextToken()).isNotNull();
+
+ ListEmailTemplatesResponse rest = sesV2.listEmailTemplates(ListEmailTemplatesRequest.builder()
+ .nextToken(first.nextToken()).build());
+
+ assertThat(rest.templatesMetadata()).extracting(EmailTemplateMetadata::templateName)
+ .doesNotContain(first.templatesMetadata().get(0).name());
+ }
+}
diff --git a/docs/services/ses.md b/docs/services/ses.md
index 63ec1c4fff..dd026a55f2 100644
--- a/docs/services/ses.md
+++ b/docs/services/ses.md
@@ -442,4 +442,6 @@ 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.
+
DKIM follows AWS's domain-centric model. A **domain** identity carries DKIM tokens (generated at verification, stable across `VerifyDomainDkim` calls); its `DkimVerificationStatus` tracks **DNS record detection** — it transitions to `Success` when the expected `<token>._domainkey.<domain>` CNAMEs are present in the Route53 emulation, not when DKIM is enabled. An **email** identity has no DKIM of its own: its `DkimAttributes` (`SigningEnabled`, `Status`, `Tokens`) are inherited from its parent domain identity when one is registered. The parent is the exact domain after the `@` (verified against AWS): a verified `example.com` covers `[email protected]` but not `[email protected]` unless `mail.example.com` is itself a registered identity. `SetIdentityDkimEnabled` / `PutEmailIdentityDkimAttributes` only toggle the signing flag (they no longer force the verification status); `PutEmailIdentityDkimSigningAttributes` sets the signing origin (`AWS_SES` Easy DKIM — regenerating tokens when the key length changes — or `EXTERNAL` BYODKIM).
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/Pagination.java b/src/main/java/io/github/hectorvent/floci/core/common/Pagination.java
index 2339d12d53..9545c07a92 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/Pagination.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/Pagination.java
@@ -39,9 +39,30 @@ public final class Pagination {
"maxResults must be between 1 and " + maxResultsLimit, 400);
}
int limit = maxResults != null ? maxResults : defaultPageSize;
+ return slice(all, cursorOf, limit,
+ decodeCursor(nextToken, "", token -> new AwsException(errorCode, "Invalid nextToken.", 400)), "");
+ }
+
+ /**
+ * For callers that validate the page size and render token errors themselves, because the
+ * wording differs per operation. Every cursor is prefixed with {@code namespace}, so a token
+ * minted for another namespace is refused instead of being read as a position in this list,
+ * while two operations listing the same resources can share one namespace and accept each
+ * other's tokens.
+ */
+ public static <T> PaginatedResult<T> paginate(List<T> all, Function<T, String> cursorOf,
+ int limit, String nextToken, String namespace,
+ Function<String, AwsException> invalidToken) {
+ if (limit < 1) {
+ throw new IllegalArgumentException("limit must be at least 1, was " + limit);
+ }
+ String prefix = namespace + ":";
+ return slice(all, cursorOf, limit, decodeCursor(nextToken, prefix, invalidToken), prefix);
+ }
+ private static <T> PaginatedResult<T> slice(List<T> all, Function<T, String> cursorOf, int limit,
+ String after, String tokenPrefix) {
List<T> sorted = all.stream().sorted(Comparator.comparing(cursorOf)).collect(Collectors.toList());
- String after = decodeToken(nextToken, errorCode);
int start = 0;
if (after != null) {
for (int i = 0; i < sorted.size(); i++) {
@@ -54,8 +75,8 @@ public final class Pagination {
}
List<T> page = sorted.stream().skip(start).limit(limit).collect(Collectors.toList());
String token = null;
- if (start + limit < sorted.size() && !page.isEmpty()) {
- token = encodeToken(cursorOf.apply(page.get(page.size() - 1)));
+ if (limit < sorted.size() - start && !page.isEmpty()) {
+ token = encodeToken(tokenPrefix + cursorOf.apply(page.get(page.size() - 1)));
}
return new PaginatedResult<>(page, token);
}
@@ -82,14 +103,20 @@ public final class Pagination {
return Base64.getUrlEncoder().withoutPadding().encodeToString(cursor.getBytes(StandardCharsets.UTF_8));
}
- private static String decodeToken(String token, String errorCode) {
+ private static String decodeCursor(String token, String prefix,
+ Function<String, AwsException> invalidToken) {
if (token == null || token.isEmpty()) {
return null;
}
+ String decoded;
try {
- return new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8);
+ decoded = new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
- throw new AwsException(errorCode, "Invalid nextToken.", 400);
+ throw invalidToken.apply(token);
+ }
+ if (!decoded.startsWith(prefix)) {
+ throw invalidToken.apply(token);
}
+ return decoded.substring(prefix.length());
}
}
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 4afeae59db..66ad6bbf57 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
@@ -5,7 +5,6 @@ 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.PaginatedResult;
-import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.ses.model.ExportJob;
import jakarta.inject.Inject;
@@ -21,8 +20,6 @@ import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
-import java.time.Instant;
-
import static io.github.hectorvent.floci.services.ses.SesV2Json.intMemberOrAbsent;
import static io.github.hectorvent.floci.services.ses.SesV2Json.putTimestamp;
import static io.github.hectorvent.floci.services.ses.SesV2Json.readOptionBody;
@@ -42,14 +39,6 @@ import static io.github.hectorvent.floci.services.ses.SesV2Json.stringMemberOrAb
@Consumes(MediaType.APPLICATION_JSON)
public class SesExportJobController {
- private static final int DEFAULT_PAGE_SIZE = 100;
- /**
- * A page no emulator will ever fill, so a larger {@code PageSize} can be clamped instead of
- * refused. The paginator adds this to the page offset as an int, so {@code Integer.MAX_VALUE}
- * would overflow that sum and report a further page that does not exist.
- */
- private static final int MAX_PAGE_SIZE = 1_000_000;
-
private final SesExportJobService exportJobService;
private final SesAccountService accountService;
private final RegionResolver regionResolver;
@@ -116,18 +105,12 @@ public class SesExportJobController {
JsonNode request = readOptionBody(objectMapper, body);
String sourceType = stringMemberOrAbsent(request, "ExportSourceType");
String jobStatus = stringMemberOrAbsent(request, "JobStatus");
- String nextToken = stringMemberOrAbsent(request, "NextToken");
- // PageSize carries no bound in the model, so a large one is clamped rather than refused;
- // only a value below 1 is an error, and the default applies when it is absent.
Integer pageSize = intMemberOrAbsent(request, "PageSize");
- if (pageSize != null && pageSize > MAX_PAGE_SIZE) {
- pageSize = MAX_PAGE_SIZE;
- }
-
- PaginatedResult<ExportJob> page = Pagination.paginate(
+ String nextToken = stringMemberOrAbsent(request, "NextToken");
+ PaginatedResult<ExportJob> page = SesListPaging.V2_LIST_EXPORT_JOBS.page(
exportJobService.listExportJobs(region, sourceType, jobStatus),
- SesExportJobController::cursor, pageSize, nextToken, DEFAULT_PAGE_SIZE,
- MAX_PAGE_SIZE, "BadRequestException");
+ job -> SesListPaging.newestFirst(job.getCreatedTimestamp(), job.getJobId()),
+ pageSize, nextToken);
ObjectNode result = objectMapper.createObjectNode();
ArrayNode jobs = result.putArray("ExportJobs");
@@ -139,9 +122,7 @@ public class SesExportJobController {
putTimestamp(node, "CreatedTimestamp", job.getCreatedTimestamp());
putTimestamp(node, "CompletedTimestamp", job.getCompletedTimestamp());
}
- if (page.nextToken() != null) {
- result.put("NextToken", page.nextToken());
- }
+ result.put("NextToken", page.nextToken());
return Response.ok(result).build();
}
@@ -152,15 +133,4 @@ public class SesExportJobController {
exportJobService.cancelExportJob(region, jobId);
return Response.ok(objectMapper.createObjectNode()).build();
}
-
- /**
- * The shared paginator orders by the cursor ascending, and AWS returns the newest job first, so
- * the cursor counts time backwards. The job id breaks ties between jobs created in the same
- * millisecond.
- */
- private static String cursor(ExportJob job) {
- Instant created = job.getCreatedTimestamp();
- long descending = Long.MAX_VALUE - (created == null ? 0L : created.toEpochMilli());
- return String.format("%019d#%s", descending, job.getJobId());
- }
}
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 522a4de558..09335b47c2 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
@@ -26,7 +26,6 @@ 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;
@@ -393,9 +392,6 @@ 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()))
- // Newest first, as AWS returns them.
- .sorted(Comparator.comparing(ExportJob::getCreatedTimestamp).reversed()
- .thenComparing(ExportJob::getJobId))
.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
new file mode 100644
index 0000000000..674bf3dd82
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesListPaging.java
@@ -0,0 +1,131 @@
+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.
+ */
+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,
+ token -> invalidParameterValue("Invalid PageToken <" + token + ">."),
+ false),
+
+ V2_LIST_EXPORT_JOBS(Namespace.EXPORT_JOB, 100, 100,
+ size -> badRequest("PageSize must be between 1 and 100"),
+ token -> badRequest("Failed to deserialize token. "),
+ true);
+
+ private static final class Namespace {
+ static final String TEMPLATE = "template";
+ static final String EXPORT_JOB = "export-job";
+ }
+
+ private final String namespace;
+ private final int defaultPageSize;
+ private final int maxPageSize;
+ private final Function<Integer, AwsException> outOfRange;
+ private final Function<String, AwsException> invalidToken;
+ private final boolean emptyTokenInvalid;
+
+ SesListPaging(String namespace, int defaultPageSize, int maxPageSize,
+ Function<Integer, AwsException> outOfRange, Function<String, AwsException> invalidToken,
+ boolean emptyTokenInvalid) {
+ this.namespace = namespace;
+ this.defaultPageSize = defaultPageSize;
+ this.maxPageSize = maxPageSize;
+ this.outOfRange = outOfRange;
+ this.invalidToken = invalidToken;
+ this.emptyTokenInvalid = emptyTokenInvalid;
+ }
+
+ <T> PaginatedResult<T> page(List<T> all, Function<T, String> 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);
+ }
+
+ int pageSize(Integer requested) {
+ if (requested == null) {
+ return defaultPageSize;
+ }
+ if (requested < 1 || requested > maxPageSize) {
+ if (outOfRange == null) {
+ return maxPageSize;
+ }
+ throw outOfRange.apply(requested);
+ }
+ return requested;
+ }
+
+ /** Newest first, as SES lists templates and export jobs; the id orders equal timestamps. */
+ static String newestFirst(Instant created, String id) {
+ long descending = Long.MAX_VALUE - (created == null ? 0L : created.toEpochMilli());
+ 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()) {
+ return null;
+ }
+ try {
+ return Integer.valueOf(raw);
+ } catch (NumberFormatException e) {
+ throw new AwsException("SerializationException",
+ "'" + raw + "' can not be converted to Integer", 400);
+ }
+ }
+
+ /**
+ * A Query-protocol page size. Unlike the REST JSON query string, a present but empty value is
+ * refused, and a value that is not an int is refused without a message.
+ */
+ static Integer parseQueryProtocolPageSize(String raw) {
+ if (raw == null) {
+ return null;
+ }
+ if (raw.isEmpty()) {
+ throw new AwsException("MalformedInput", "missing value for decimal type", 400);
+ }
+ try {
+ return Integer.valueOf(raw);
+ } catch (NumberFormatException e) {
+ throw new AwsException("MalformedInput", null, 400);
+ }
+ }
+
+ private static AwsException badRequest(String message) {
+ return new AwsException("BadRequestException", message, 400);
+ }
+
+ private static AwsException invalidParameterValue(String message) {
+ return new AwsException("InvalidParameterValue", message, 400);
+ }
+}
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 c69cd19f58..6deb2f4666 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
@@ -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.AwsNamespaces;
import io.github.hectorvent.floci.core.common.AwsQueryResponse;
+import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.services.ses.model.BulkEmailEntry;
import io.github.hectorvent.floci.services.ses.model.BulkEmailEntryResult;
@@ -110,7 +111,7 @@ public class SesQueryHandler {
case "UpdateTemplate" -> handleUpdateTemplate(params, region);
case "GetTemplate" -> handleGetTemplate(params, region);
case "DeleteTemplate" -> handleDeleteTemplate(params, region);
- case "ListTemplates" -> handleListTemplates(region);
+ case "ListTemplates" -> handleListTemplates(params, region);
case "SendTemplatedEmail" -> handleSendTemplatedEmail(params, region);
case "SendBulkTemplatedEmail" -> handleSendBulkTemplatedEmail(params, region);
case "TestRenderTemplate" -> handleTestRenderTemplate(params, region);
@@ -563,10 +564,13 @@ public class SesQueryHandler {
return Response.ok(AwsQueryResponse.envelopeEmptyResult("DeleteTemplate", AwsNamespaces.SES)).build();
}
- private Response handleListTemplates(String region) {
- List<EmailTemplate> templates = templateService.listTemplates(region);
- var xml = new XmlBuilder().start("TemplatesMetadata");
- for (EmailTemplate t : templates) {
+ private Response handleListTemplates(MultivaluedMap<String, String> params, String region) {
+ PaginatedResult<EmailTemplate> page = SesListPaging.V1_LIST_TEMPLATES.page(
+ templateService.listTemplates(region), SesListPaging::templateCursor,
+ SesListPaging.parseQueryProtocolPageSize(getParam(params, "MaxItems")),
+ getParam(params, "NextToken"));
+ XmlBuilder xml = new XmlBuilder().start("TemplatesMetadata");
+ for (EmailTemplate t : page.items()) {
xml.start("member")
.elem("Name", t.getTemplateName());
if (t.getCreatedTimestamp() != null) {
@@ -575,6 +579,7 @@ public class SesQueryHandler {
xml.end("member");
}
xml.end("TemplatesMetadata");
+ xml.elem("NextToken", page.nextToken());
return Response.ok(AwsQueryResponse.envelope("ListTemplates", 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 96c385c324..0b61f4f269 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
@@ -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.EmailTemplate;
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;
@@ -85,17 +87,22 @@ public class SesTemplateController {
@GET
@Path("/templates")
- public Response listEmailTemplates(@Context HttpHeaders headers) {
+ public Response listEmailTemplates(@Context HttpHeaders headers,
+ @QueryParam("PageSize") String pageSize,
+ @QueryParam("NextToken") String nextToken) {
String region = regionResolver.resolveRegion(headers);
- List<EmailTemplate> templates = templateService.listTemplates(region);
+ PaginatedResult<EmailTemplate> page = SesListPaging.V2_LIST_EMAIL_TEMPLATES.page(
+ templateService.listTemplates(region), SesListPaging::templateCursor,
+ SesListPaging.parseQueryPageSize(pageSize), nextToken);
ObjectNode result = objectMapper.createObjectNode();
ArrayNode items = result.putArray("TemplatesMetadata");
- for (EmailTemplate t : templates) {
+ for (EmailTemplate t : page.items()) {
ObjectNode item = objectMapper.createObjectNode();
item.put("TemplateName", t.getTemplateName());
putTimestamp(item, "CreatedTimestamp", t.getCreatedTimestamp());
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/SesTemplateService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateService.java
index 1c2783a4bf..6471a08374 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
@@ -13,12 +13,12 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.security.SecureRandom;
+import java.time.Clock;
import java.time.Instant;
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;
@@ -52,18 +52,20 @@ public class SesTemplateService {
private final StorageBackend<String, EmailTemplate> templateStore;
private final ObjectMapper objectMapper;
private final SecureRandom boundaryRandom;
+ private final Clock clock;
@Inject
- public SesTemplateService(StorageFactory storageFactory, ObjectMapper objectMapper) {
+ public SesTemplateService(StorageFactory storageFactory, ObjectMapper objectMapper, Clock clock) {
this(storageFactory.create("ses", "ses-templates.json",
- new TypeReference<Map<String, EmailTemplate>>() {}), objectMapper, new SecureRandom());
+ new TypeReference<Map<String, EmailTemplate>>() {}), objectMapper, new SecureRandom(), clock);
}
SesTemplateService(StorageBackend<String, EmailTemplate> templateStore,
- ObjectMapper objectMapper, SecureRandom boundaryRandom) {
+ ObjectMapper objectMapper, SecureRandom boundaryRandom, Clock clock) {
this.templateStore = templateStore;
this.objectMapper = objectMapper;
this.boundaryRandom = boundaryRandom;
+ this.clock = clock;
}
public EmailTemplate createTemplate(EmailTemplate template, String region) {
@@ -74,7 +76,7 @@ public class SesTemplateService {
throw new AwsException("AlreadyExists",
"Template " + template.getTemplateName() + " already exists.", 400);
}
- Instant now = Instant.now();
+ Instant now = Instant.now(clock);
template.setCreatedTimestamp(now);
template.setLastUpdatedTimestamp(now);
templateStore.put(key, template);
@@ -95,7 +97,7 @@ public class SesTemplateService {
.orElseThrow(() -> new AwsException("TemplateDoesNotExist",
"Template " + template.getTemplateName() + " does not exist.", 400));
template.setCreatedTimestamp(existing.getCreatedTimestamp());
- template.setLastUpdatedTimestamp(Instant.now());
+ template.setLastUpdatedTimestamp(Instant.now(clock));
// Tags are managed exclusively via Tag/UntagResource — preserve them on update (copied,
// so the two objects never share a list instance).
template.setTags(new ArrayList<>(existing.getTags()));
@@ -116,12 +118,7 @@ public class SesTemplateService {
public List<EmailTemplate> listTemplates(String region) {
String prefix = "template::" + region + "::";
- List<EmailTemplate> all = new ArrayList<>(templateStore.scan(k -> k.startsWith(prefix)));
- all.sort(Comparator.comparing(EmailTemplate::getCreatedTimestamp,
- Comparator.nullsLast(Comparator.naturalOrder()))
- .thenComparing(EmailTemplate::getTemplateName,
- Comparator.nullsLast(Comparator.naturalOrder())));
- return all;
+ return templateStore.scan(k -> k.startsWith(prefix));
}
/**
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PaginationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PaginationTest.java
new file mode 100644
index 0000000000..2de6025e74
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/PaginationTest.java
@@ -0,0 +1,95 @@
+package io.github.hectorvent.floci.core.common;
+
+import org.junit.jupiter.api.Test;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import java.util.List;
+import java.util.function.Function;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.startsWith;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class PaginationTest {
+
+ private static final List<String> ITEMS = List.of("c", "a", "b");
+ private static final AwsException INVALID = new AwsException("BadRequestException", "bad", 400);
+ private static final Function<String, AwsException> INVALID_TOKEN = token -> INVALID;
+
+ @Test
+ void namespacedPaging_walksTheSortedListAndEndsWithoutAToken() {
+ PaginatedResult<String> first = page(2, null, "ns");
+ assertThat(first.items(), contains("a", "b"));
+ assertThat(decode(first.nextToken()), startsWith("ns:"));
+
+ PaginatedResult<String> last = page(2, first.nextToken(), "ns");
+ assertThat(last.items(), contains("c"));
+ assertNull(last.nextToken());
+ }
+
+ @Test
+ void namespacedPaging_refusesATokenFromAnotherNamespace() {
+ String foreign = page(1, null, "other").nextToken();
+
+ assertSame(INVALID, assertThrows(AwsException.class, () -> page(1, foreign, "ns")));
+ }
+
+ @Test
+ void namespacedPaging_refusesATokenThatDoesNotDecode() {
+ assertSame(INVALID, assertThrows(AwsException.class, () -> page(1, "!!!", "ns")));
+ }
+
+ @Test
+ void namespacedPaging_passesTheRawTokenToTheErrorFactory() {
+ AwsException e = assertThrows(AwsException.class, () -> Pagination.paginate(ITEMS,
+ Function.identity(), 1, "!!!", "ns",
+ token -> new AwsException("BadRequestException", "bad " + token, 400)));
+ assertEquals("bad !!!", e.getMessage());
+ }
+
+ @Test
+ void namespacedPaging_treatsAnEmptyTokenAsTheFirstPage() {
+ assertThat(page(1, "", "ns").items(), contains("a"));
+ }
+
+ @Test
+ void namespacedPaging_refusesALimitBelowOne() {
+ assertThrows(IllegalArgumentException.class, () -> page(0, null, "ns"));
+ }
+
+ @Test
+ void paging_aLimitNearIntMaxDoesNotReportAFurtherPage() {
+ String afterFirst = page(1, null, "ns").nextToken();
+
+ PaginatedResult<String> rest = page(Integer.MAX_VALUE, afterFirst, "ns");
+ assertThat(rest.items(), contains("b", "c"));
+ assertNull(rest.nextToken());
+ }
+
+ @Test
+ void legacyPaging_keepsItsTokenFormatAndError() {
+ PaginatedResult<String> first = Pagination.paginate(ITEMS, Function.identity(), 1, null, 3,
+ "ValidationException");
+ assertEquals("a", decode(first.nextToken()));
+ assertThat(Pagination.paginate(ITEMS, Function.identity(), 1, first.nextToken(), 3,
+ "ValidationException").items(), contains("b"));
+
+ AwsException e = assertThrows(AwsException.class, () -> Pagination.paginate(ITEMS,
+ Function.identity(), 1, "!!!", 3, "ValidationException"));
+ assertEquals("ValidationException", e.getErrorCode());
+ assertEquals("Invalid nextToken.", e.getMessage());
+ }
+
+ private static PaginatedResult<String> page(int limit, String token, String namespace) {
+ return Pagination.paginate(ITEMS, Function.identity(), limit, token, namespace, INVALID_TOKEN);
+ }
+
+ private static String decode(String token) {
+ return new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesExportJobV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesExportJobV2IntegrationTest.java
index 74fa24f509..0bc61e7dbc 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesExportJobV2IntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesExportJobV2IntegrationTest.java
@@ -19,6 +19,7 @@ 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;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -395,7 +396,17 @@ class SesExportJobV2IntegrationTest {
void malformedPagingAndResultLimitsAreRefused() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"PageSize\": \"ten\"}")
- .when().post("/v2/email/list-export-jobs").then().statusCode(400);
+ .when().post("/v2/email/list-export-jobs").then().statusCode(400)
+ .body("__type", equalTo("SerializationException"));
+ // The body is deserialized before any member is validated, so a mistyped member wins.
+ given().contentType("application/json").header("Authorization", AUTH)
+ .body("{\"JobStatus\": \"BOGUS\", \"PageSize\": \"ten\"}")
+ .when().post("/v2/email/list-export-jobs").then().statusCode(400)
+ .body("__type", equalTo("SerializationException"));
+ given().contentType("application/json").header("Authorization", AUTH)
+ .body("{\"ExportSourceType\": \"BOGUS\", \"NextToken\": 5}")
+ .when().post("/v2/email/list-export-jobs").then().statusCode(400)
+ .body("__type", equalTo("SerializationException"));
create("""
{"ExportDataSource": {"MessageInsightsDataSource":
@@ -454,18 +465,21 @@ class SesExportJobV2IntegrationTest {
@Test
@Order(16)
- void listExportJobs_acceptsAPageSizeAboveTheDefault() {
- // PageSize carries no bound in the model, so a large page is a normal request.
- given().contentType("application/json").header("Authorization", AUTH)
- .body("{\"PageSize\": 250}")
- .when().post("/v2/email/list-export-jobs").then().statusCode(200);
-
- given().contentType("application/json").header("Authorization", AUTH)
- .body("{\"PageSize\": 0}")
- .when().post("/v2/email/list-export-jobs").then().statusCode(400);
+ void listExportJobs_boundsPagingTheWaySesDoes() {
+ for (String size : new String[] {"0", "101", "250"}) {
+ given().contentType("application/json").header("Authorization", AUTH)
+ .body("{\"PageSize\": %s}".formatted(size))
+ .when().post("/v2/email/list-export-jobs").then().statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo("PageSize must be between 1 and 100"));
+ }
+ for (String token : new String[] {"garbage", ""}) {
+ given().contentType("application/json").header("Authorization", AUTH)
+ .body("{\"NextToken\": \"%s\"}".formatted(token))
+ .when().post("/v2/email/list-export-jobs").then().statusCode(400)
+ .body("message", equalTo("Failed to deserialize token. "));
+ }
- // A page size at the int ceiling is clamped, not refused, and must not report a further
- // page: the paginator adds the page size to the offset as an int.
String token = given().contentType("application/json").header("Authorization", AUTH)
.body("{\"PageSize\": 1}")
.when().post("/v2/email/list-export-jobs").then().statusCode(200)
@@ -473,9 +487,10 @@ class SesExportJobV2IntegrationTest {
assertNotNull(token, "the fixture needs more than one job for this to mean anything");
given().contentType("application/json").header("Authorization", AUTH)
- .body("{\"PageSize\": 2147483647, \"NextToken\": \"%s\"}".formatted(token))
+ .body("{\"PageSize\": 100, \"NextToken\": \"%s\"}".formatted(token))
.when().post("/v2/email/list-export-jobs").then().statusCode(200)
- .body("$", not(hasKey("NextToken")));
+ .body("$", hasKey("NextToken"))
+ .body("NextToken", nullValue());
}
@Test
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
new file mode 100644
index 0000000000..78bd5d498d
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesListPagingTest.java
@@ -0,0 +1,127 @@
+package io.github.hectorvent.floci.services.ses;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.PaginatedResult;
+import org.junit.jupiter.api.Test;
+
+import java.time.Instant;
+import java.util.List;
+import java.util.function.Function;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.lessThan;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class SesListPagingTest {
+
+ private static final List<String> ITEMS = List.of("a", "b", "c");
+
+ @Test
+ void pageSize_defaultsPerOperation() {
+ assertEquals(10, SesListPaging.V2_LIST_EMAIL_TEMPLATES.pageSize(null));
+ assertEquals(10, SesListPaging.V1_LIST_TEMPLATES.pageSize(null));
+ assertEquals(100, SesListPaging.V2_LIST_EXPORT_JOBS.pageSize(null));
+ assertEquals(1, SesListPaging.V2_LIST_EMAIL_TEMPLATES.pageSize(1));
+ assertEquals(100, SesListPaging.V2_LIST_EMAIL_TEMPLATES.pageSize(100));
+ }
+
+ @Test
+ void pageSize_outOfRangeIsRefusedWithThePerOperationMessage() {
+ assertError("BadRequestException", "The page size must be between 1 and 100",
+ () -> SesListPaging.V2_LIST_EMAIL_TEMPLATES.pageSize(101));
+ assertError("BadRequestException", "PageSize must be between 1 and 100",
+ () -> SesListPaging.V2_LIST_EXPORT_JOBS.pageSize(0));
+ }
+
+ @Test
+ void pageSize_v1TemplatesServeTheBoundForAnOutOfRangeValue() {
+ for (int size : new int[] {0, -1, 101, Integer.MAX_VALUE}) {
+ assertEquals(100, SesListPaging.V1_LIST_TEMPLATES.pageSize(size));
+ }
+ }
+
+ @Test
+ void templateTokens_areSharedBetweenV1AndV2AndRefusedByExportJobs() {
+ String v1Token = page(SesListPaging.V1_LIST_TEMPLATES, 1, null).nextToken();
+
+ assertThat(page(SesListPaging.V2_LIST_EMAIL_TEMPLATES, 1, v1Token).items(), contains("b"));
+ assertError("BadRequestException", "Failed to deserialize token. ",
+ () -> page(SesListPaging.V2_LIST_EXPORT_JOBS, 1, v1Token));
+ }
+
+ @Test
+ void invalidToken_messagesQuoteTheToken() {
+ assertError("BadRequestException", "Invalid PageToken <garbage>.",
+ () -> page(SesListPaging.V2_LIST_EMAIL_TEMPLATES, 1, "garbage"));
+ assertError("InvalidParameterValue", "Invalid PageToken <garbage>.",
+ () -> page(SesListPaging.V1_LIST_TEMPLATES, 1, "garbage"));
+ }
+
+ @Test
+ void emptyToken_isTheFirstPageForTemplatesAndAnErrorForExportJobs() {
+ assertThat(page(SesListPaging.V2_LIST_EMAIL_TEMPLATES, 1, "").items(), contains("a"));
+ assertError("BadRequestException", "Failed to deserialize token. ",
+ () -> page(SesListPaging.V2_LIST_EXPORT_JOBS, 1, ""));
+ }
+
+ @Test
+ void lastPage_hasNoToken() {
+ PaginatedResult<String> page = page(SesListPaging.V2_LIST_EMAIL_TEMPLATES, 3, null);
+ assertThat(page.items(), contains("a", "b", "c"));
+ assertNull(page.nextToken());
+ }
+
+ @Test
+ void newestFirst_ordersByTimeDescendingThenById() {
+ Instant earlier = Instant.parse("2026-09-25T00:00:00Z");
+ Instant later = earlier.plusMillis(1);
+
+ assertThat(SesListPaging.newestFirst(later, "z"),
+ lessThan(SesListPaging.newestFirst(earlier, "a")));
+ assertThat(SesListPaging.newestFirst(later, "a"),
+ lessThan(SesListPaging.newestFirst(later, "b")));
+ }
+
+ @Test
+ void parseQueryPageSize_refusesANonInteger() {
+ assertNull(SesListPaging.parseQueryPageSize(null));
+ assertNull(SesListPaging.parseQueryPageSize(""));
+ assertEquals(5, SesListPaging.parseQueryPageSize("5"));
+ assertError("SerializationException", "'99999999999' can not be converted to Integer",
+ () -> SesListPaging.parseQueryPageSize("99999999999"));
+ }
+
+ @Test
+ void parseQueryProtocolPageSize_refusesANonIntegerWithoutAMessage() {
+ assertNull(SesListPaging.parseQueryProtocolPageSize(null));
+ assertEquals(5, SesListPaging.parseQueryProtocolPageSize("5"));
+ assertError("MalformedInput", null, () -> SesListPaging.parseQueryProtocolPageSize("1.5"));
+ }
+
+ @Test
+ void parseQueryProtocolPageSize_refusesAnEmptyValue() {
+ assertError("MalformedInput", "missing value for decimal type",
+ () -> SesListPaging.parseQueryProtocolPageSize(""));
+ }
+
+ @Test
+ void pageSize_isReportedBeforeTheToken() {
+ assertError("BadRequestException", "PageSize must be between 1 and 100",
+ () -> SesListPaging.V2_LIST_EXPORT_JOBS.page(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"));
+ }
+
+ private static PaginatedResult<String> page(SesListPaging paging, int size, String token) {
+ return paging.page(ITEMS, Function.identity(), size, token);
+ }
+
+ private static void assertError(String code, String message, Runnable call) {
+ AwsException e = assertThrows(AwsException.class, call::run);
+ assertEquals(code, e.getErrorCode());
+ assertEquals(message, e.getMessage());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.java
index bd18b4df3a..64bf552777 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.java
@@ -168,7 +168,7 @@ final class SesServiceTestBuilder {
return new SesService(
identityService,
sentEmailService,
- new SesTemplateService(templateStore, objectMapper, new SecureRandom()),
+ new SesTemplateService(templateStore, objectMapper, new SecureRandom(), clock),
configSetService,
suppressionService,
new SesDedicatedIpService(dedicatedIpPoolStore),
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesTemplatePagingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesTemplatePagingIntegrationTest.java
new file mode 100644
index 0000000000..998dc9d08d
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesTemplatePagingIntegrationTest.java
@@ -0,0 +1,223 @@
+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 ListTemplates} and v2 {@code ListEmailTemplates} lists, which share one
+ * token namespace. Runs in its own region so the three templates are the whole list.
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class SesTemplatePagingIntegrationTest {
+
+ private static final String AUTH =
+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/ap-southeast-2/ses/aws4_request";
+ // A second region holding eleven templates, one more than the default page.
+ private static final String AUTH_ELEVEN =
+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/ap-southeast-3/ses/aws4_request";
+ private static final String V1_ROOT = "ListTemplatesResponse.ListTemplatesResult.";
+
+ @Test
+ @Order(1)
+ void createTemplatesOutOfNameOrder() {
+ // The test-scope MutableClock advances on every read, so each template gets a later
+ // creation time and the order below is by time, not by the name tiebreak.
+ for (String name : new String[] {"page-b", "page-c", "page-a"}) {
+ given().contentType("application/json").header("Authorization", AUTH)
+ .body("""
+ {"TemplateName": "%s", "TemplateContent": {"Subject": "s", "Text": "t"}}
+ """.formatted(name))
+ .when().post("/v2/email/templates").then().statusCode(200);
+ }
+ }
+
+ @Test
+ @Order(2)
+ void v2_walksNewestFirstAndEndsOnANullToken() {
+ String token = given().header("Authorization", AUTH).queryParam("PageSize", 1)
+ .when().get("/v2/email/templates").then().statusCode(200)
+ .body("TemplatesMetadata.TemplateName", contains("page-a"))
+ .body("NextToken", notNullValue())
+ .extract().path("NextToken");
+
+ token = given().header("Authorization", AUTH)
+ .queryParam("PageSize", 1).queryParam("NextToken", token)
+ .when().get("/v2/email/templates").then().statusCode(200)
+ .body("TemplatesMetadata.TemplateName", contains("page-c"))
+ .extract().path("NextToken");
+
+ given().header("Authorization", AUTH)
+ .queryParam("PageSize", 1).queryParam("NextToken", token)
+ .when().get("/v2/email/templates").then().statusCode(200)
+ .body("TemplatesMetadata.TemplateName", contains("page-b"))
+ .body("$", hasKey("NextToken"))
+ .body("NextToken", nullValue());
+ }
+
+ @Test
+ @Order(3)
+ void v2_withoutPagingReturnsTheWholeListAndANullToken() {
+ given().header("Authorization", AUTH)
+ .when().get("/v2/email/templates").then().statusCode(200)
+ .body("TemplatesMetadata.TemplateName", contains("page-a", "page-c", "page-b"))
+ .body("$", hasKey("NextToken"))
+ .body("NextToken", nullValue());
+
+ given().header("Authorization", AUTH).queryParam("NextToken", "").queryParam("PageSize", "")
+ .when().get("/v2/email/templates").then().statusCode(200)
+ .body("TemplatesMetadata.TemplateName", contains("page-a", "page-c", "page-b"));
+ }
+
+ @Test
+ @Order(4)
+ void v2_refusesAPageSizeOutsideOneToAHundred() {
+ for (int size : new int[] {0, 101}) {
+ given().header("Authorization", AUTH).queryParam("PageSize", size)
+ .when().get("/v2/email/templates").then().statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo("The page size must be between 1 and 100"));
+ }
+ given().header("Authorization", AUTH).queryParam("PageSize", 100)
+ .when().get("/v2/email/templates").then().statusCode(200);
+ }
+
+ @Test
+ @Order(5)
+ void v2_refusesANonIntegerPageSizeAndAnUnreadableToken() {
+ given().header("Authorization", AUTH).queryParam("PageSize", "abc")
+ .when().get("/v2/email/templates").then().statusCode(400)
+ .body("__type", equalTo("SerializationException"))
+ .body("message", equalTo("'abc' can not be converted to Integer"));
+
+ given().header("Authorization", AUTH).queryParam("NextToken", "garbage")
+ .when().get("/v2/email/templates").then().statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo("Invalid PageToken <garbage>."));
+ }
+
+ @Test
+ @Order(6)
+ void v1_walksNewestFirstAndOmitsTheTokenOnTheLastPage() {
+ XmlPath first = listV1("1", null);
+ assertThat(first.getList(V1_ROOT + "TemplatesMetadata.member.Name"), contains("page-a"));
+ String token = first.getString(V1_ROOT + "NextToken");
+
+ XmlPath second = listV1("1", token);
+ assertThat(second.getList(V1_ROOT + "TemplatesMetadata.member.Name"), contains("page-c"));
+
+ given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH)
+ .formParam("Action", "ListTemplates").formParam("MaxItems", "1")
+ .formParam("NextToken", second.getString(V1_ROOT + "NextToken"))
+ .when().post("/").then().statusCode(200)
+ .body(containsString("<Name>page-b</Name>"))
+ .body(not(containsString("<NextToken>")));
+ }
+
+ @Test
+ @Order(7)
+ void v1_servesAnOutOfRangeMaxItemsInsteadOfRefusingIt() {
+ for (String size : new String[] {"0", "-1", "1001"}) {
+ XmlPath page = listV1(size, null);
+ assertThat(page.getList(V1_ROOT + "TemplatesMetadata.member.Name"),
+ contains("page-a", "page-c", "page-b"));
+ }
+ }
+
+ @Test
+ @Order(8)
+ void v1_refusesANonIntegerMaxItemsAndAnUnreadableToken() {
+ given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH)
+ .formParam("Action", "ListTemplates").formParam("MaxItems", "abc")
+ .when().post("/").then().statusCode(400)
+ .body(containsString("<Code>MalformedInput</Code>"))
+ .body(not(containsString("<Message>")));
+
+ given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH)
+ .formParam("Action", "ListTemplates").formParam("MaxItems", "")
+ .when().post("/").then().statusCode(400)
+ .body(containsString("<Code>MalformedInput</Code>"))
+ .body(containsString("<Message>missing value for decimal type</Message>"));
+
+ given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH)
+ .formParam("Action", "ListTemplates").formParam("NextToken", "garbage")
+ .when().post("/").then().statusCode(400)
+ .body(containsString("<Code>InvalidParameterValue</Code>"))
+ .body(containsString("<Message>Invalid PageToken &lt;garbage&gt;.</Message>"));
+ }
+
+ @Test
+ @Order(9)
+ void tokensCarryOverBetweenV1AndV2() {
+ String v1Token = listV1("1", null).getString(V1_ROOT + "NextToken");
+ given().header("Authorization", AUTH).queryParam("NextToken", v1Token)
+ .when().get("/v2/email/templates").then().statusCode(200)
+ .body("TemplatesMetadata.TemplateName", contains("page-c", "page-b"));
+
+ String v2Token = given().header("Authorization", AUTH).queryParam("PageSize", 1)
+ .when().get("/v2/email/templates").then().statusCode(200)
+ .extract().path("NextToken");
+ assertThat(listV1(null, v2Token).getList(V1_ROOT + "TemplatesMetadata.member.Name"),
+ contains("page-c", "page-b"));
+ }
+
+ @Test
+ @Order(10)
+ void withoutAPageSizeBothListsServeTen() {
+ for (int i = 0; i < 11; i++) {
+ given().contentType("application/json").header("Authorization", AUTH_ELEVEN)
+ .body("""
+ {"TemplateName": "eleven-%02d", "TemplateContent": {"Subject": "s", "Text": "t"}}
+ """.formatted(i))
+ .when().post("/v2/email/templates").then().statusCode(200);
+ }
+
+ given().header("Authorization", AUTH_ELEVEN)
+ .when().get("/v2/email/templates").then().statusCode(200)
+ .body("TemplatesMetadata", hasSize(10))
+ .body("NextToken", notNullValue());
+
+ XmlPath v1Default = given().contentType("application/x-www-form-urlencoded")
+ .header("Authorization", AUTH_ELEVEN).formParam("Action", "ListTemplates")
+ .when().post("/").then().statusCode(200).extract().xmlPath();
+ assertThat(v1Default.getList(V1_ROOT + "TemplatesMetadata.member.Name"), hasSize(10));
+ assertThat(v1Default.getString(V1_ROOT + "NextToken"), not(emptyOrNullString()));
+
+ // An out-of-range MaxItems is served the bound, not the default.
+ XmlPath outOfRange = given().contentType("application/x-www-form-urlencoded")
+ .header("Authorization", AUTH_ELEVEN)
+ .formParam("Action", "ListTemplates").formParam("MaxItems", "0")
+ .when().post("/").then().statusCode(200).extract().xmlPath();
+ assertThat(outOfRange.getList(V1_ROOT + "TemplatesMetadata.member.Name"), hasSize(11));
+ }
+
+ private static XmlPath listV1(String maxItems, String nextToken) {
+ RequestSpecification request = given()
+ .contentType("application/x-www-form-urlencoded").header("Authorization", AUTH)
+ .formParam("Action", "ListTemplates");
+ 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/SesTemplateServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesTemplateServiceTest.java
index f887009bf9..19dfe79f3f 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
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.ses.model.EmailTemplate;
import io.github.hectorvent.floci.services.ses.model.Tag;
+import io.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.provider.MethodSource;
@@ -14,9 +15,13 @@ import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.ParameterizedTest;
import java.security.SecureRandom;
+import java.time.Clock;
+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;
@@ -37,7 +42,8 @@ class SesTemplateServiceTest {
@BeforeEach
void setUp() {
- service = new SesTemplateService(new InMemoryStorage<>(), new ObjectMapper(), new SecureRandom());
+ service = new SesTemplateService(new InMemoryStorage<>(), new ObjectMapper(), new SecureRandom(),
+ Clock.systemUTC());
}
private static EmailTemplate template(String name) {
@@ -98,15 +104,27 @@ class SesTemplateServiceTest {
}
@Test
- void list_isSortedByCreationAndPerRegion() {
+ void create_andUpdate_stampTheInjectedClock() {
+ SesTemplateService ticking = new SesTemplateService(new InMemoryStorage<>(), new ObjectMapper(),
+ new SecureRandom(), new MutableClock());
+
+ Instant created = ticking.createTemplate(template("welcome"), REGION).getCreatedTimestamp();
+ ticking.updateTemplate(template("welcome"), REGION);
+
+ EmailTemplate stored = ticking.getTemplate("welcome", REGION);
+ assertEquals(created, stored.getCreatedTimestamp());
+ assertEquals(created.plusMillis(1), stored.getLastUpdatedTimestamp());
+ }
+
+ @Test
+ void list_isPerRegion() {
service.createTemplate(template("a"), REGION);
service.createTemplate(template("b"), REGION);
service.createTemplate(template("other"), "eu-west-1");
- List<EmailTemplate> list = service.listTemplates(REGION);
- assertEquals(2, list.size());
- assertEquals("a", list.get(0).getTemplateName());
- assertEquals("b", list.get(1).getTemplateName());
+ List<String> names = service.listTemplates(REGION).stream()
+ .map(EmailTemplate::getTemplateName).toList();
+ assertThat(names, containsInAnyOrder("a", "b"));
}
@Test