feat(ses): paginate the tenant and import job lists (#4819)

* feat(ses): paginate the tenant and import job lists

Page ListTenants, ListTenantResources, ListResourceTenants and ListImportJobs
on the shared SES paging, each with its own token namespace, and delete
SesTenantService.validateListPaging. The tenant lists answer the probed SES
rules: PageSize 1 to 100 with the Smithy validation messages, an empty
NextToken refused with its Smithy message before the tenant or resource is
looked up, an unreadable token answered "Invalid Next Token", tenants listed
by name, a tenant's resources by ARN and a resource's tenants in association
order. ListImportJobs could not be probed and is modelled on the tenant lists,
keeping Floci's oldest-first order. Without a PageSize all four lists serve up
to 100, a Floci assumption where nothing could be measured.

* fix(ses): follow the probed order, aggregation and token binding on the tenant lists

A second probe of real SES showed three differences on ListTenantResources and
ListResourceTenants: the tenant or resource is looked up, and the filter
checked, before the page size and token; a page size outside the bound and an
empty NextToken are reported together in one validation message; and a token
is refused once the tenant, resource or filter changes. ListImportJobs, which
cannot be probed, follows the same rules. The service docs keep the per-list
paging detail and gain a paragraph for these four lists.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-10-01 13:10:03 -04:00
1 parent bcf1045536
commit a22e65f993
14 files changed
+988 -91

No files matched your search

@@ -0,0 +1,131 @@
package io.github.hectorvent.floci.services.ses;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.util.ArrayList;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* Paging of the v2 {@code ListImportJobs} list: oldest job first, the Smithy validation messages
* borrowed from the tenant lists, the empty-token error and the filter being validated first. Runs
* in its own region so the jobs created here are the whole list; the test-scope ticking clock
* separates their creation stamps. The jobs delete addresses that were never suppressed, so they
* leave no state behind whatever their outcome.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SesImportJobPagingIntegrationTest {
private static final String REGION = "eu-central-2";
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/" + REGION + "/ses/aws4_request";
private static final String BUCKET = "ses-import-job-paging-it";
private static final String PAGE_SIZE_BELOW_ONE = "Value '0' at 'pageSize' failed to satisfy constraint: "
+ "Member must have value greater than or equal to 1";
private static final String PAGE_SIZE_ABOVE_BOUND = "Value '101' at 'pageSize' failed to satisfy constraint: "
+ "Member must have value less than or equal to 100";
private static final String EMPTY_TOKEN = "Value '' at 'nextToken' failed to satisfy constraint: "
+ "Member must have length greater than or equal to 1";
private static final List<String> created = new ArrayList<>();
private static RequestSpecification v2() {
return given().contentType("application/json").header("Authorization", AUTH);
}
@Test
@Order(1)
void createThreeJobs() {
given().when().put("/" + BUCKET).then().statusCode(200);
given().contentType("text/plain").body("never-suppressed@example.com\n")
.when().put("/" + BUCKET + "/delete.csv").then().statusCode(200);
for (int i = 0; i < 3; i++) {
created.add(v2().body("""
{"ImportDataSource":{"S3Url":"s3://%s/delete.csv","DataFormat":"CSV"},
"ImportDestination":{"SuppressionListDestination":{"SuppressionListImportAction":"DELETE"}}}
""".formatted(BUCKET))
.when().post("/v2/email/import-jobs").then().statusCode(200)
.extract().path("JobId"));
}
}
@Test
@Order(2)
void walksOldestFirstAndEndsOnANullToken() {
String token = v2().body("{\"PageSize\":1}")
.when().post("/v2/email/import-jobs/list").then().statusCode(200)
.body("ImportJobs.JobId", contains(created.get(0)))
.body("NextToken", notNullValue())
.extract().path("NextToken");
v2().body("{\"PageSize\":5,\"NextToken\":\"" + token + "\"}")
.when().post("/v2/email/import-jobs/list").then().statusCode(200)
.body("ImportJobs.JobId", contains(created.get(1), created.get(2)))
.body("$", hasKey("NextToken"))
.body("NextToken", nullValue());
}
@Test
@Order(3)
void outOfRangeSizesAndBadTokensAnswerTheSmithyMessages() {
v2().body("{\"PageSize\":0}")
.when().post("/v2/email/import-jobs/list").then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("1 validation error detected: " + PAGE_SIZE_BELOW_ONE));
v2().body("{\"PageSize\":101}")
.when().post("/v2/email/import-jobs/list").then().statusCode(400)
.body("message", equalTo("1 validation error detected: " + PAGE_SIZE_ABOVE_BOUND));
v2().body("{\"NextToken\":\"garbage\"}")
.when().post("/v2/email/import-jobs/list").then().statusCode(400)
.body("message", equalTo("Invalid Next Token"));
v2().body("{\"NextToken\":\"\"}")
.when().post("/v2/email/import-jobs/list").then().statusCode(400)
.body("message", equalTo("1 validation error detected: " + EMPTY_TOKEN));
v2().body("{\"PageSize\":0,\"NextToken\":\"\"}")
.when().post("/v2/email/import-jobs/list").then().statusCode(400)
.body("message", equalTo("2 validation errors detected: " + EMPTY_TOKEN + "; " + PAGE_SIZE_BELOW_ONE));
}
@Test
@Order(4)
void aTokenIsBoundToItsFilter() {
String token = v2().body("{\"ImportDestinationType\":\"SUPPRESSION_LIST\",\"PageSize\":1}")
.when().post("/v2/email/import-jobs/list").then().statusCode(200).extract().path("NextToken");
v2().body("{\"ImportDestinationType\":\"SUPPRESSION_LIST\",\"NextToken\":\"" + token + "\"}")
.when().post("/v2/email/import-jobs/list").then().statusCode(200)
.body("ImportJobs.JobId", contains(created.get(1), created.get(2)));
v2().body("{\"NextToken\":\"" + token + "\"}")
.when().post("/v2/email/import-jobs/list").then().statusCode(400)
.body("message", equalTo("Invalid Next Token"));
}
@Test
@Order(5)
void theFilterIsValidatedBeforeThePage() {
v2().body("{\"ImportDestinationType\":\"EXPORT\",\"PageSize\":0}")
.when().post("/v2/email/import-jobs/list").then().statusCode(400)
.body("message", equalTo("1 validation error detected: Value at 'importDestinationType' "
+ "failed to satisfy constraint: Member must satisfy enum value set: "
+ "[SUPPRESSION_LIST, CONTACT_LIST]"));
}
@Test
@Order(6)
void cleanup() {
given().when().delete("/" + BUCKET + "/delete.csv").then().statusCode(204);
given().when().delete("/" + BUCKET).then().statusCode(204);
}
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ses;
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.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
@@ -10,6 +11,7 @@ import io.github.hectorvent.floci.services.ses.model.Contact;
import io.github.hectorvent.floci.services.ses.model.ImportJob;
import io.github.hectorvent.floci.services.ses.model.Topic;
import io.github.hectorvent.floci.services.ses.model.TopicPreference;
import io.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -278,7 +280,7 @@ class SesImportJobServiceTest {
assertBadRequest(() -> service.createSuppressionListImportJob(REGION, ACCOUNT, "s3://bucket", "CSV", "PUT"));
assertBadRequest(() -> service.createSuppressionListImportJob(REGION, ACCOUNT, url("a.csv"), "XML", "PUT"));
assertBadRequest(() -> service.createSuppressionListImportJob(REGION, ACCOUNT, url("a.csv"), "CSV", "UPSERT"));
assertTrue(service.listImportJobs(REGION, null, null, null).isEmpty());
assertTrue(service.listImportJobs(REGION, null).isEmpty());
}
@Test
@@ -288,7 +290,7 @@ class SesImportJobServiceTest {
assertEquals("NotFoundException", e.getErrorCode());
// Probed against real AWS: this path words it differently from the contact-list APIs.
assertEquals("ContactList <missing> doesn't exist", e.getMessage());
assertTrue(service.listImportJobs(REGION, null, null, null).isEmpty());
assertTrue(service.listImportJobs(REGION, null).isEmpty());
}
@Test
@@ -321,13 +323,37 @@ class SesImportJobServiceTest {
service.createSuppressionListImportJob(REGION, ACCOUNT, url("a.csv"), "CSV", "PUT");
service.createContactListImportJob(REGION, ACCOUNT, url("c.csv"), "CSV", LIST, "PUT");
assertEquals(2, service.listImportJobs(REGION, null, null, null).size());
assertEquals(1, service.listImportJobs(REGION, "CONTACT_LIST", 10, null).size());
assertEquals(1, service.listImportJobs(REGION, "SUPPRESSION_LIST", null, null).size());
assertTrue(service.listImportJobs("us-east-1", null, null, null).isEmpty());
assertBadRequest(() -> service.listImportJobs(REGION, "EXPORT", null, null));
assertBadRequest(() -> service.listImportJobs(REGION, null, 0, null));
assertBadRequest(() -> service.listImportJobs(REGION, null, null, "token"));
assertEquals(2, service.listImportJobs(REGION, null).size());
assertEquals(1, service.listImportJobs(REGION, "CONTACT_LIST", SesListPaging.V2_LIST_IMPORT_JOBS, 10, null)
.items().size());
assertEquals(1, service.listImportJobs(REGION, "SUPPRESSION_LIST").size());
assertTrue(service.listImportJobs("us-east-1", null).isEmpty());
assertBadRequest(() -> service.listImportJobs(REGION, "EXPORT"));
assertBadRequest(() -> service.listImportJobs(REGION, null, SesListPaging.V2_LIST_IMPORT_JOBS, 0, null));
assertBadRequest(() -> service.listImportJobs(REGION, null, SesListPaging.V2_LIST_IMPORT_JOBS, null, "token"));
}
@Test
void listImportJobs_oldestFirst_andPagesOnThatOrder() {
stubObject("a.csv", "alice@example.com,BOUNCE\n");
// A ticking clock separates the creation stamps, so creation order can beat job-id order.
SesImportJobService ticking = new SesImportJobService(jobStore, s3Service, suppressionService,
contactService, new ObjectMapper().findAndRegisterModules(), new MutableClock(), Runnable::run);
List<String> created = new ArrayList<>();
for (int i = 0; i < 5; i++) {
created.add(ticking.createSuppressionListImportJob(REGION, ACCOUNT, url("a.csv"), "CSV", "PUT").getJobId());
}
assertEquals(created, ticking.listImportJobs(REGION, null).stream().map(ImportJob::getJobId).toList());
PaginatedResult<ImportJob> first = ticking.listImportJobs(REGION, null,
SesListPaging.V2_LIST_IMPORT_JOBS, 2, null);
assertEquals(created.subList(0, 2), first.items().stream().map(ImportJob::getJobId).toList());
assertNotNull(first.nextToken());
PaginatedResult<ImportJob> rest = ticking.listImportJobs(REGION, null,
SesListPaging.V2_LIST_IMPORT_JOBS, 10, first.nextToken());
assertEquals(created.subList(2, 5), rest.items().stream().map(ImportJob::getJobId).toList());
assertNull(rest.nextToken());
}
@Test
@@ -393,7 +419,7 @@ class SesImportJobServiceTest {
}
assertEquals(SesImportJobService.MAX_CONCURRENT_JOBS, rejected.get());
assertEquals(SesImportJobService.MAX_CONCURRENT_JOBS, parked.listImportJobs(REGION, null, null, null).size());
assertEquals(SesImportJobService.MAX_CONCURRENT_JOBS, parked.listImportJobs(REGION, null).size());
}
@Test
@@ -3,6 +3,8 @@ 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 org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.time.Instant;
import java.util.List;
@@ -19,6 +21,9 @@ class SesListPagingTest {
private static final String REGION = "us-east-1";
private static final List<String> ITEMS = List.of("a", "b", "c");
private static final String EMPTY_TOKEN_VIOLATION = "Value '' at 'nextToken' failed to satisfy constraint: "
+ "Member must have length greater than or equal to 1";
private static final String EMPTY_TOKEN_MESSAGE = "1 validation error detected: " + EMPTY_TOKEN_VIOLATION;
@Test
void pageSize_defaultsPerOperation() {
@@ -191,6 +196,103 @@ class SesListPagingTest {
() -> SesListPaging.V2_LIST_EMAIL_TEMPLATES.page(REGION, ITEMS, Function.identity(), 0, "garbage"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("tenantStyleLists")
void tenantStyle_pageSizeDefaultsToTheBound(SesListPaging paging) {
assertEquals(100, paging.pageSize(null));
assertEquals(1, paging.pageSize(1));
assertEquals(100, paging.pageSize(100));
}
@ParameterizedTest(name = "{0}")
@MethodSource("tenantStyleLists")
void tenantStyle_outOfRangePageSizeAnswersTheSmithyMessageWithTheValue(SesListPaging paging) {
assertError("BadRequestException", pageSizeMessage(0, "greater than or equal to 1"),
() -> paging.pageSize(0));
assertError("BadRequestException", pageSizeMessage(-7, "greater than or equal to 1"),
() -> paging.pageSize(-7));
assertError("BadRequestException", pageSizeMessage(101, "less than or equal to 100"),
() -> paging.pageSize(101));
assertError("BadRequestException", pageSizeMessage(0, "greater than or equal to 1"),
() -> page(paging, 0, "garbage"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("tenantStyleLists")
void tenantStyle_unreadableAndEmptyTokensAreRefusedDifferently(SesListPaging paging) {
assertError("BadRequestException", "Invalid Next Token", () -> page(paging, 1, "garbage"));
assertError("BadRequestException", EMPTY_TOKEN_MESSAGE, () -> page(paging, 1, ""));
}
@ParameterizedTest(name = "{0}")
@MethodSource("tenantStyleLists")
void tenantStyle_aTokenIsRefusedByEveryOtherKind(SesListPaging minting) {
String token = page(minting, 1, null).nextToken();
assertThat(page(minting, 1, token).items(), contains("b"));
for (SesListPaging other : tenantStyleLists()) {
if (other != minting) {
assertError("BadRequestException", "Invalid Next Token", () -> page(other, 1, token));
}
}
assertError("BadRequestException", "Failed to deserialize token. ",
() -> page(SesListPaging.V2_LIST_EXPORT_JOBS, 1, token));
}
@ParameterizedTest(name = "{0}")
@MethodSource("tenantStyleLists")
void tenantStyle_aBadPageSizeAndAnEmptyTokenAreReportedTogether(SesListPaging paging) {
assertError("BadRequestException", "2 validation errors detected: " + EMPTY_TOKEN_VIOLATION + "; "
+ pageSizeViolation(0, "greater than or equal to 1"), () -> page(paging, 0, ""));
assertError("BadRequestException", "2 validation errors detected: " + EMPTY_TOKEN_VIOLATION + "; "
+ pageSizeViolation(101, "less than or equal to 100"), () -> page(paging, 101, ""));
}
@Test
void scope_bindsATokenToWhatTheRequestSelected() {
SesListPaging paging = SesListPaging.V2_LIST_TENANT_RESOURCES;
String token = paging.page(REGION, "/tenant-a", ITEMS, Function.identity(), 1, null).nextToken();
assertThat(paging.page(REGION, "/tenant-a", ITEMS, Function.identity(), 1, token).items(), contains("b"));
assertError("BadRequestException", "Invalid Next Token",
() -> paging.page(REGION, "/tenant-b", ITEMS, Function.identity(), 1, token));
assertError("BadRequestException", "Invalid Next Token", () -> page(paging, 1, token));
}
@Test
void oldestFirst_ordersByTimeAscendingThenById() {
Instant earlier = Instant.parse("2026-09-25T00:00:00Z");
Instant later = earlier.plusMillis(1);
assertThat(SesListPaging.oldestFirst(earlier, "z"),
lessThan(SesListPaging.oldestFirst(later, "a")));
assertThat(SesListPaging.oldestFirst(later, "a"),
lessThan(SesListPaging.oldestFirst(later, "b")));
// The cursor is compared as text, so a stamp with fewer digits must still sort first.
assertThat(SesListPaging.oldestFirst(Instant.ofEpochSecond(9), "a"),
lessThan(SesListPaging.oldestFirst(Instant.ofEpochSecond(10), "a")));
// Two stamps inside one millisecond keep their order, whatever the ids.
assertThat(SesListPaging.oldestFirst(earlier.plusNanos(1), "z"),
lessThan(SesListPaging.oldestFirst(earlier.plusNanos(2), "a")));
// A missing stamp sorts last, as the unpaged lists order it.
assertThat(SesListPaging.oldestFirst(later, "z"),
lessThan(SesListPaging.oldestFirst(null, "a")));
}
private static List<SesListPaging> tenantStyleLists() {
return List.of(SesListPaging.V2_LIST_TENANTS, SesListPaging.V2_LIST_TENANT_RESOURCES,
SesListPaging.V2_LIST_RESOURCE_TENANTS, SesListPaging.V2_LIST_IMPORT_JOBS);
}
private static String pageSizeMessage(int value, String constraint) {
return "1 validation error detected: " + pageSizeViolation(value, constraint);
}
private static String pageSizeViolation(int value, String constraint) {
return "Value '" + value + "' at 'pageSize' failed to satisfy constraint: Member must have value "
+ constraint;
}
private static PaginatedResult<String> page(SesListPaging paging, int size, String token) {
return paging.page(REGION, ITEMS, Function.identity(), size, token);
}
@@ -0,0 +1,232 @@
package io.github.hectorvent.floci.services.ses;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.stream.Stream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* Paging of the v2 {@code ListTenants}, {@code ListTenantResources} and {@code ListResourceTenants}
* lists as probed on real SES: the orders (tenants by name, a tenant's resources by ARN, a resource's
* tenants in association order), the Smithy validation messages, the lookup and filter coming before
* the page validation, and a token bound to the request it came from. Runs in its own region so the
* tenants created here are the whole list; the test-scope ticking clock separates the association
* stamps.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SesTenantPagingIntegrationTest {
private static final String REGION = "af-south-1";
// Only a token is sent there and it is refused, so no state lands in this region.
private static final String OTHER_REGION = "eu-west-1";
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/" + REGION + "/ses/aws4_request";
private static final String ARN_PREFIX = "arn:aws:ses:" + REGION + ":000000000000:";
private static final String PAGE_SIZE_BELOW_ONE = "Value '0' at 'pageSize' failed to satisfy constraint: "
+ "Member must have value greater than or equal to 1";
private static final String PAGE_SIZE_ABOVE_BOUND = "Value '101' at 'pageSize' failed to satisfy constraint: "
+ "Member must have value less than or equal to 100";
private static final String EMPTY_TOKEN = "Value '' at 'nextToken' failed to satisfy constraint: "
+ "Member must have length greater than or equal to 1";
private static RequestSpecification v2() {
return given().contentType("application/json").header("Authorization", AUTH);
}
@Test
@Order(1)
void createTenantsAndResourcesOutOfOrder() {
// Tenants are created out of name order, and associated to the shared identity in yet
// another order, so a by-name walk and an association-order walk cannot both pass by luck.
for (String tenant : new String[] {"page-c", "page-a", "page-b"}) {
v2().body("{\"TenantName\":\"" + tenant + "\"}")
.when().post("/v2/email/tenants").then().statusCode(200);
}
v2().body("{\"EmailIdentity\":\"shared.page.test\"}")
.when().post("/v2/email/identities").then().statusCode(200);
for (String tenant : new String[] {"page-b", "page-c", "page-a"}) {
associate(tenant, ARN_PREFIX + "identity/shared.page.test");
}
for (String identity : new String[] {"c.page.test", "a.page.test", "b.page.test"}) {
v2().body("{\"EmailIdentity\":\"" + identity + "\"}")
.when().post("/v2/email/identities").then().statusCode(200);
associate("page-a", ARN_PREFIX + "identity/" + identity);
}
}
@Test
@Order(2)
void listTenants_walksByNameAndEndsOnANullToken() {
String token = v2().body("{\"PageSize\":1}")
.when().post("/v2/email/tenants/list").then().statusCode(200)
.body("Tenants.TenantName", contains("page-a"))
.body("NextToken", notNullValue())
.extract().path("NextToken");
v2().body("{\"PageSize\":5,\"NextToken\":\"" + token + "\"}")
.when().post("/v2/email/tenants/list").then().statusCode(200)
.body("Tenants.TenantName", contains("page-b", "page-c"))
.body("$", hasKey("NextToken"))
.body("NextToken", nullValue());
}
@Test
@Order(3)
void listTenantResources_walksByArn() {
String token = v2().body("{\"TenantName\":\"page-a\",\"PageSize\":1}")
.when().post("/v2/email/tenants/resources/list").then().statusCode(200)
.body("TenantResources.ResourceArn", contains(ARN_PREFIX + "identity/a.page.test"))
.body("NextToken", notNullValue())
.extract().path("NextToken");
v2().body("{\"TenantName\":\"page-a\",\"PageSize\":10,\"NextToken\":\"" + token + "\"}")
.when().post("/v2/email/tenants/resources/list").then().statusCode(200)
.body("TenantResources.ResourceArn", contains(ARN_PREFIX + "identity/b.page.test",
ARN_PREFIX + "identity/c.page.test", ARN_PREFIX + "identity/shared.page.test"))
.body("NextToken", nullValue());
}
@Test
@Order(4)
void listResourceTenants_walksInAssociationOrder() {
String token = v2().body("{\"ResourceArn\":\"" + ARN_PREFIX + "identity/shared.page.test\",\"PageSize\":1}")
.when().post("/v2/email/resources/tenants/list").then().statusCode(200)
.body("ResourceTenants.TenantName", contains("page-b"))
.body("NextToken", notNullValue())
.extract().path("NextToken");
v2().body("{\"ResourceArn\":\"" + ARN_PREFIX + "identity/shared.page.test\",\"NextToken\":\"" + token + "\"}")
.when().post("/v2/email/resources/tenants/list").then().statusCode(200)
.body("ResourceTenants.TenantName", contains("page-c", "page-a"))
.body("NextToken", nullValue());
}
@Test
@Order(5)
void tokensDoNotCrossBetweenTheThreeLists() {
String tenantToken = v2().body("{\"PageSize\":1}")
.when().post("/v2/email/tenants/list").then().statusCode(200).extract().path("NextToken");
v2().body("{\"TenantName\":\"page-a\",\"NextToken\":\"" + tenantToken + "\"}")
.when().post("/v2/email/tenants/resources/list").then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("Invalid Next Token"));
v2().body("{\"ResourceArn\":\"" + ARN_PREFIX + "identity/shared.page.test\",\"NextToken\":\""
+ tenantToken + "\"}")
.when().post("/v2/email/resources/tenants/list").then().statusCode(400)
.body("message", equalTo("Invalid Next Token"));
// The two association lists page the same records, so each must still refuse the other's token.
String resourceToken = v2().body("{\"TenantName\":\"page-a\",\"PageSize\":1}")
.when().post("/v2/email/tenants/resources/list").then().statusCode(200).extract().path("NextToken");
v2().body("{\"ResourceArn\":\"" + ARN_PREFIX + "identity/shared.page.test\",\"NextToken\":\""
+ resourceToken + "\"}")
.when().post("/v2/email/resources/tenants/list").then().statusCode(400)
.body("message", equalTo("Invalid Next Token"));
}
@Test
@Order(6)
void aTokenReplayedInAnotherRegionIsRefused() {
String token = v2().body("{\"PageSize\":1}")
.when().post("/v2/email/tenants/list").then().statusCode(200).extract().path("NextToken");
given().contentType("application/json")
.header("Authorization", AUTH.replace(REGION, OTHER_REGION))
.body("{\"NextToken\":\"" + token + "\"}")
.when().post("/v2/email/tenants/list").then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("Invalid Next Token"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("lists")
@Order(7)
void outOfRangeSizesAndBadTokensAnswerTheSmithyMessages(String operation, String path, String subject) {
v2().body("{" + subject + "\"PageSize\":0}")
.when().post(path).then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("1 validation error detected: " + PAGE_SIZE_BELOW_ONE));
v2().body("{" + subject + "\"PageSize\":101}")
.when().post(path).then().statusCode(400)
.body("message", equalTo("1 validation error detected: " + PAGE_SIZE_ABOVE_BOUND));
v2().body("{" + subject + "\"NextToken\":\"garbage\"}")
.when().post(path).then().statusCode(400)
.body("message", equalTo("Invalid Next Token"));
v2().body("{" + subject + "\"NextToken\":\"\"}")
.when().post(path).then().statusCode(400)
.body("message", equalTo("1 validation error detected: " + EMPTY_TOKEN));
v2().body("{" + subject + "\"PageSize\":0,\"NextToken\":\"\"}")
.when().post(path).then().statusCode(400)
.body("message", equalTo("2 validation errors detected: " + EMPTY_TOKEN + "; " + PAGE_SIZE_BELOW_ONE));
}
private static Stream<Arguments> lists() {
return Stream.of(
Arguments.of("ListTenants", "/v2/email/tenants/list", ""),
Arguments.of("ListTenantResources", "/v2/email/tenants/resources/list",
"\"TenantName\":\"page-a\","),
Arguments.of("ListResourceTenants", "/v2/email/resources/tenants/list",
"\"ResourceArn\":\"" + ARN_PREFIX + "identity/shared.page.test\","));
}
@Test
@Order(8)
void theLookupAndTheFilterPrecedeThePageValidation() {
v2().body("{\"TenantName\":\"ghost-tenant\",\"PageSize\":0,\"NextToken\":\"\"}")
.when().post("/v2/email/tenants/resources/list").then().statusCode(404)
.body("__type", equalTo("NotFoundException"));
v2().body("{\"TenantName\":\"ghost-tenant\",\"Filter\":{\"RESOURCE_TYPE\":\"NOPE\"}}")
.when().post("/v2/email/tenants/resources/list").then().statusCode(404)
.body("__type", equalTo("NotFoundException"));
v2().body("{\"TenantName\":\"page-a\",\"Filter\":{\"RESOURCE_TYPE\":\"NOPE\"},\"PageSize\":0}")
.when().post("/v2/email/tenants/resources/list").then().statusCode(400)
.body("message", equalTo("Invalid resource type NOPE specified."));
v2().body("{\"ResourceArn\":\"" + ARN_PREFIX + "identity/ghost.page.test\",\"PageSize\":0}")
.when().post("/v2/email/resources/tenants/list").then().statusCode(404)
.body("__type", equalTo("NotFoundException"));
}
@Test
@Order(9)
void aTokenIsBoundToItsTenantFilterAndResource() {
String resourceToken = v2().body("{\"TenantName\":\"page-a\",\"PageSize\":1}")
.when().post("/v2/email/tenants/resources/list").then().statusCode(200).extract().path("NextToken");
v2().body("{\"TenantName\":\"page-b\",\"NextToken\":\"" + resourceToken + "\"}")
.when().post("/v2/email/tenants/resources/list").then().statusCode(400)
.body("message", equalTo("Invalid Next Token"));
v2().body("{\"TenantName\":\"page-a\",\"Filter\":{\"RESOURCE_TYPE\":\"identity\"},\"NextToken\":\""
+ resourceToken + "\"}")
.when().post("/v2/email/tenants/resources/list").then().statusCode(400)
.body("message", equalTo("Invalid Next Token"));
String tenantToken = v2().body("{\"ResourceArn\":\"" + ARN_PREFIX
+ "identity/shared.page.test\",\"PageSize\":1}")
.when().post("/v2/email/resources/tenants/list").then().statusCode(200).extract().path("NextToken");
v2().body("{\"ResourceArn\":\"" + ARN_PREFIX + "identity/a.page.test\",\"NextToken\":\""
+ tenantToken + "\"}")
.when().post("/v2/email/resources/tenants/list").then().statusCode(400)
.body("message", equalTo("Invalid Next Token"));
}
private static void associate(String tenant, String arn) {
v2().body("{\"TenantName\":\"" + tenant + "\",\"ResourceArn\":\"" + arn + "\"}")
.when().post("/v2/email/tenants/resources").then().statusCode(200);
}
}
@@ -1,9 +1,12 @@
package io.github.hectorvent.floci.services.ses;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.ses.model.Tag;
import io.github.hectorvent.floci.services.ses.model.Tenant;
import io.github.hectorvent.floci.services.ses.model.TenantResourceAssociation;
import io.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -13,6 +16,8 @@ import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -558,18 +563,72 @@ class SesTenantServiceTest {
}
@Test
void validateFilterAndPaging_matchAwsMessages() {
void validateFilter_matchesAwsMessages() {
assertEquals("Invalid resource type NOPE specified.",
assertThrows(AwsException.class,
() -> SesTenantService.validateResourceTypeFilter("NOPE")).getMessage());
assertEquals("Invalid resource type EMAIL_IDENTITY specified.",
assertThrows(AwsException.class,
() -> SesTenantService.validateResourceTypeFilter("EMAIL_IDENTITY")).getMessage());
assertTrue(assertThrows(AwsException.class,
() -> SesTenantService.validateListPaging(0, null))
.getMessage().contains("greater than or equal to 1"));
assertEquals("Invalid Next Token",
assertThrows(AwsException.class,
() -> SesTenantService.validateListPaging(null, "garbage")).getMessage());
}
@Test
void listTenants_byName_andPagesOnThatOrder() {
for (String name : new String[] {"delta", "alpha", "echo", "charlie", "bravo"}) {
service.createTenant(name, List.of(), ACCOUNT, REGION);
}
assertEquals(List.of("alpha", "bravo", "charlie", "delta", "echo"),
service.listTenants(REGION).stream().map(Tenant::tenantName).toList());
PaginatedResult<Tenant> first = service.listTenants(REGION, SesListPaging.V2_LIST_TENANTS, 2, null);
assertEquals(List.of("alpha", "bravo"), first.items().stream().map(Tenant::tenantName).toList());
assertNotNull(first.nextToken());
PaginatedResult<Tenant> rest = service.listTenants(REGION, SesListPaging.V2_LIST_TENANTS, 10,
first.nextToken());
assertEquals(List.of("charlie", "delta", "echo"), rest.items().stream().map(Tenant::tenantName).toList());
assertNull(rest.nextToken());
}
@Test
void listTenantResources_pagesByArn() {
Tenant tenant = service.createTenant("acme", List.of(), ACCOUNT, REGION);
for (String domain : new String[] {"c.example.com", "a.example.com", "b.example.com"}) {
service.associate(tenant, identityRef(domain), REGION, () -> {});
}
PaginatedResult<TenantResourceAssociation> first = service.listTenantResources(tenant, null, REGION,
SesListPaging.V2_LIST_TENANT_RESOURCES, 2, null);
assertEquals(List.of(identityRef("a.example.com").arn(), identityRef("b.example.com").arn()),
first.items().stream().map(TenantResourceAssociation::resourceArn).toList());
PaginatedResult<TenantResourceAssociation> rest = service.listTenantResources(tenant, null, REGION,
SesListPaging.V2_LIST_TENANT_RESOURCES, 2, first.nextToken());
assertEquals(List.of(identityRef("c.example.com").arn()),
rest.items().stream().map(TenantResourceAssociation::resourceArn).toList());
assertNull(rest.nextToken());
}
@Test
void listResourceTenants_inAssociationOrder_andPagesOnThatOrder() {
// A ticking clock separates the association stamps, so association order can beat name order.
SesTenantService ticking = new SesTenantService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new MutableClock(), new SecureRandom());
for (String name : new String[] {"zulu", "alpha", "mike"}) {
Tenant tenant = ticking.createTenant(name, List.of(), ACCOUNT, REGION);
ticking.associate(tenant, identityRef("example.com"), REGION, () -> {});
}
assertEquals(List.of("zulu", "alpha", "mike"),
ticking.listResourceTenants(identityRef("example.com"), REGION).stream()
.map(TenantResourceAssociation::tenantName).toList());
PaginatedResult<TenantResourceAssociation> first = ticking.listResourceTenants(identityRef("example.com"),
REGION, SesListPaging.V2_LIST_RESOURCE_TENANTS, 2, null);
assertEquals(List.of("zulu", "alpha"),
first.items().stream().map(TenantResourceAssociation::tenantName).toList());
PaginatedResult<TenantResourceAssociation> rest = ticking.listResourceTenants(identityRef("example.com"),
REGION, SesListPaging.V2_LIST_RESOURCE_TENANTS, 2, first.nextToken());
assertEquals(List.of("mike"), rest.items().stream().map(TenantResourceAssociation::tenantName).toList());
assertNull(rest.nextToken());
}
}