diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesImportJobPagingTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesImportJobPagingTest.java new file mode 100644 index 0000000000..70ffd2c467 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesImportJobPagingTest.java @@ -0,0 +1,95 @@ +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.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.CreateBucketRequest; +import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; +import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.sesv2.SesV2Client; +import software.amazon.awssdk.services.sesv2.model.CreateImportJobRequest; +import software.amazon.awssdk.services.sesv2.model.DataFormat; +import software.amazon.awssdk.services.sesv2.model.ImportDataSource; +import software.amazon.awssdk.services.sesv2.model.ImportDestination; +import software.amazon.awssdk.services.sesv2.model.ImportJobSummary; +import software.amazon.awssdk.services.sesv2.model.ListImportJobsRequest; +import software.amazon.awssdk.services.sesv2.model.ListImportJobsResponse; +import software.amazon.awssdk.services.sesv2.model.SuppressionListDestination; +import software.amazon.awssdk.services.sesv2.model.SuppressionListImportAction; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Paging of the SES v2 import-job list through the SDK paginator: every job created here is listed + * exactly once across small pages. The jobs delete an address that was never suppressed, so they + * leave no state behind whatever their outcome; import jobs themselves cannot be deleted. + */ +@DisplayName("SES import job list paging") +class SesImportJobPagingTest { + + private static final String KEY = "delete.csv"; + + private static SesV2Client sesV2; + private static S3Client s3; + private static String bucket; + private static List jobIds; + + @BeforeAll + static void setup() { + sesV2 = TestFixtures.sesV2Client(); + s3 = TestFixtures.s3Client(); + bucket = "floci-ses-import-paging-" + TestFixtures.uniqueName(); + jobIds = new ArrayList<>(); + s3.createBucket(CreateBucketRequest.builder().bucket(bucket).build()); + s3.putObject(PutObjectRequest.builder().bucket(bucket).key(KEY).build(), + RequestBody.fromString("never-suppressed@example.com\n")); + for (int i = 0; i < 3; i++) { + jobIds.add(sesV2.createImportJob(CreateImportJobRequest.builder() + .importDataSource(ImportDataSource.builder() + .s3Url("s3://" + bucket + "/" + KEY).dataFormat(DataFormat.CSV).build()) + .importDestination(ImportDestination.builder() + .suppressionListDestination(SuppressionListDestination.builder() + .suppressionListImportAction(SuppressionListImportAction.DELETE).build()) + .build()) + .build()).jobId()); + } + } + + @AfterAll + static void cleanup() { + if (s3 != null) { + try { + s3.deleteObject(DeleteObjectRequest.builder().bucket(bucket).key(KEY).build()); + s3.deleteBucket(DeleteBucketRequest.builder().bucket(bucket).build()); + } catch (Exception ignored) { + // Best-effort cleanup; a leftover bucket does not affect other tests. + } + s3.close(); + } + if (sesV2 != null) { + sesV2.close(); + } + } + + @Test + @DisplayName("ListImportJobs paginator walks small pages over every job once") + void paginatorWalksEveryJobOnce() { + List listed = new ArrayList<>(); + for (ListImportJobsResponse page : sesV2.listImportJobsPaginator( + ListImportJobsRequest.builder().pageSize(2).build())) { + assertThat(page.importJobs()).hasSizeLessThanOrEqualTo(2); + page.importJobs().stream().map(ImportJobSummary::jobId).forEach(listed::add); + } + + assertThat(listed).doesNotHaveDuplicates(); + assertThat(listed.stream().filter(jobIds::contains)).containsExactlyInAnyOrderElementsOf(jobIds); + } +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTenantPagingTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTenantPagingTest.java new file mode 100644 index 0000000000..79d49315a8 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesTenantPagingTest.java @@ -0,0 +1,133 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import software.amazon.awssdk.services.sesv2.SesV2Client; +import software.amazon.awssdk.services.sesv2.model.CreateEmailIdentityRequest; +import software.amazon.awssdk.services.sesv2.model.CreateTenantRequest; +import software.amazon.awssdk.services.sesv2.model.CreateTenantResponse; +import software.amazon.awssdk.services.sesv2.model.CreateTenantResourceAssociationRequest; +import software.amazon.awssdk.services.sesv2.model.DeleteEmailIdentityRequest; +import software.amazon.awssdk.services.sesv2.model.DeleteTenantRequest; +import software.amazon.awssdk.services.sesv2.model.ListResourceTenantsRequest; +import software.amazon.awssdk.services.sesv2.model.ListResourceTenantsResponse; +import software.amazon.awssdk.services.sesv2.model.ListTenantResourcesRequest; +import software.amazon.awssdk.services.sesv2.model.ListTenantResourcesResponse; +import software.amazon.awssdk.services.sesv2.model.ListTenantsRequest; +import software.amazon.awssdk.services.sesv2.model.ListTenantsResponse; +import software.amazon.awssdk.services.sesv2.model.ResourceTenantMetadata; +import software.amazon.awssdk.services.sesv2.model.TenantInfo; +import software.amazon.awssdk.services.sesv2.model.TenantResource; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Paging of the SES v2 tenant lists through the SDK paginators: every tenant, tenant resource and + * resource tenant created here is listed exactly once across small pages. Tenants are reversible + * (create + delete), so cleanup restores the account. + */ +@DisplayName("SES tenant list paging") +class SesTenantPagingTest { + + private static SesV2Client sesV2; + private static List tenants; + private static List identities; + private static List identityArns; + + @BeforeAll + static void setup() { + sesV2 = TestFixtures.sesV2Client(); + String prefix = "sdk-page-" + TestFixtures.uniqueName(); + tenants = List.of(prefix + "-b", prefix + "-c", prefix + "-a"); + identities = List.of(prefix + "-b.test", prefix + "-c.test", prefix + "-a.test"); + identityArns = new ArrayList<>(); + String arnPrefix = null; + for (String tenant : tenants) { + CreateTenantResponse created = sesV2.createTenant(CreateTenantRequest.builder().tenantName(tenant).build()); + arnPrefix = created.tenantArn().substring(0, created.tenantArn().indexOf(":tenant/") + 1); + } + for (String identity : identities) { + sesV2.createEmailIdentity(CreateEmailIdentityRequest.builder().emailIdentity(identity).build()); + identityArns.add(arnPrefix + "identity/" + identity); + } + // Every identity is associated with the first tenant, and the first identity with every tenant. + for (String arn : identityArns) { + associate(tenants.get(0), arn); + } + for (String tenant : tenants.subList(1, tenants.size())) { + associate(tenant, identityArns.get(0)); + } + } + + @AfterAll + static void cleanup() { + if (sesV2 != null) { + // DeleteTenant cascades the associations, so the identities can go afterwards. + for (String tenant : tenants) { + try { + sesV2.deleteTenant(DeleteTenantRequest.builder().tenantName(tenant).build()); + } catch (Exception ignored) { + // Best-effort cleanup; a leftover tenant does not affect other tests. + } + } + for (String identity : identities) { + try { + sesV2.deleteEmailIdentity(DeleteEmailIdentityRequest.builder().emailIdentity(identity).build()); + } catch (Exception ignored) { + // Best-effort cleanup; a leftover identity does not affect other tests. + } + } + sesV2.close(); + } + } + + @Test + @DisplayName("ListTenants paginator walks small pages over every tenant once") + void listTenantsPaginatorWalksEveryTenantOnce() { + List listed = new ArrayList<>(); + for (ListTenantsResponse page : sesV2.listTenantsPaginator(ListTenantsRequest.builder().pageSize(2).build())) { + assertThat(page.tenants()).hasSizeLessThanOrEqualTo(2); + page.tenants().stream().map(TenantInfo::tenantName).forEach(listed::add); + } + + assertThat(listed).doesNotHaveDuplicates(); + assertThat(listed.stream().filter(tenants::contains)).containsExactlyInAnyOrderElementsOf(tenants); + } + + @Test + @DisplayName("ListTenantResources paginator walks small pages over every resource once") + void listTenantResourcesPaginatorWalksEveryResourceOnce() { + List listed = new ArrayList<>(); + for (ListTenantResourcesResponse page : sesV2.listTenantResourcesPaginator( + ListTenantResourcesRequest.builder().tenantName(tenants.get(0)).pageSize(2).build())) { + assertThat(page.tenantResources()).hasSizeLessThanOrEqualTo(2); + page.tenantResources().stream().map(TenantResource::resourceArn).forEach(listed::add); + } + + assertThat(listed).doesNotHaveDuplicates().containsExactlyInAnyOrderElementsOf(identityArns); + } + + @Test + @DisplayName("ListResourceTenants paginator walks small pages over every tenant once") + void listResourceTenantsPaginatorWalksEveryTenantOnce() { + List listed = new ArrayList<>(); + for (ListResourceTenantsResponse page : sesV2.listResourceTenantsPaginator( + ListResourceTenantsRequest.builder().resourceArn(identityArns.get(0)).pageSize(2).build())) { + assertThat(page.resourceTenants()).hasSizeLessThanOrEqualTo(2); + page.resourceTenants().stream().map(ResourceTenantMetadata::tenantName).forEach(listed::add); + } + + assertThat(listed).doesNotHaveDuplicates().containsExactlyInAnyOrderElementsOf(tenants); + } + + private static void associate(String tenant, String arn) { + sesV2.createTenantResourceAssociation(CreateTenantResourceAssociationRequest.builder() + .tenantName(tenant).resourceArn(arn).build()); + } +} diff --git a/docs/services/ses.md b/docs/services/ses.md index 5548e16b98..8cb9e07bd8 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -410,9 +410,9 @@ Account-level VDM (Virtual Deliverability Manager) attributes are stored per reg Account provisioning details are stored per region. `PutAccountDetails` sets `MailType` (required, ∈ {`MARKETING`, `TRANSACTIONAL`}) and `WebsiteURL` (required, 1–1000 chars) plus the optional `ContactLanguage` (∈ {`EN`, `JA`}), `UseCaseDescription` (≤5000 chars), `AdditionalContactEmailAddresses` (1–4 entries, each 6–254 chars matching `^(.+)@(.+)$`), and `ProductionAccessEnabled`. Floci stores `ProductionAccessEnabled` as given but stays production-enabled regardless (it has no sandbox), so the flag has no functional effect. Like `VdmAttributes`, `GetAccount` omits `Details` until it has been configured for the region, then echoes the stored fields under `Details` with a `ReviewDetails` block. Matching AWS, all modeled-constraint violations (null / enum / length / list) are aggregated into a single `BadRequestException` reporting every failure; a malformed (but in-range) `WebsiteURL` is reported separately as `Url contains invalid format`. Floci has no sandbox and does not run a production-access review, so `ReviewDetails.Status` is always `GRANTED`. -Tenants (multi-tenancy) are stored per region. `CreateTenant` requires a `TenantName` (1–64 chars, `[A-Za-z0-9_-]`) and accepts optional `Tags`; it returns the tenant with a generated `TenantId` (`tn-` + 30 hex), a `TenantArn` (`arn:aws:ses:::tenant//`), a `CreatedTimestamp`, and `SendingStatus` `ENABLED`. The operations use RPC-style POST subpaths (`/tenants/get`, `/tenants/list`, `/tenants/delete`); `ListTenants` returns the `TenantInfo` subset (no `Tags`/`SendingStatus`) and currently returns every tenant in a single page — `PageSize`/`NextToken` pagination is not yet implemented. A duplicate name is `AlreadyExistsException`; an unknown tenant on get/delete is `NotFoundException`. +Tenants (multi-tenancy) are stored per region. `CreateTenant` requires a `TenantName` (1–64 chars, `[A-Za-z0-9_-]`) and accepts optional `Tags`; it returns the tenant with a generated `TenantId` (`tn-` + 30 hex), a `TenantArn` (`arn:aws:ses:::tenant//`), a `CreatedTimestamp`, and `SendingStatus` `ENABLED`. The operations use RPC-style POST subpaths (`/tenants/get`, `/tenants/list`, `/tenants/delete`); `ListTenants` returns the `TenantInfo` subset (no `Tags`/`SendingStatus`). A duplicate name is `AlreadyExistsException`; an unknown tenant on get/delete is `NotFoundException`. -Tenant resource associations link a tenant to email identities, configuration sets, and email templates. Matching real AWS, the wire values for `ResourceType` — in responses and as the `Filter` `RESOURCE_TYPE` value — are the ARN segments `identity` / `configuration-set` / `template`; the SDK's `EMAIL_IDENTITY`-style enum constants are rejected, as AWS itself does. The resource must exist in the same account and region; a duplicate association is `AlreadyExistsException`, and deleting a missing one succeeds silently. Deleting a resource that still has associations is rejected, while `DeleteTenant` cascades its associations away. The list operations return a single page (no `PageSize`/`NextToken` pagination yet, like `ListTenants`). +Tenant resource associations link a tenant to email identities, configuration sets, and email templates. Matching real AWS, the wire values for `ResourceType` (in responses and as the `Filter` `RESOURCE_TYPE` value) are the ARN segments `identity` / `configuration-set` / `template`; the SDK's `EMAIL_IDENTITY`-style enum constants are rejected, as AWS itself does. The resource must exist in the same account and region; a duplicate association is `AlreadyExistsException`, and deleting a missing one succeeds silently. Deleting a resource that still has associations is rejected, while `DeleteTenant` cascades its associations away. A `TenantName` on `SendEmail`/`SendBulkEmail` makes the send tenant-scoped: the resources it uses — the From identity (the exact address identity, else its domain identity), the effective configuration set (an omitted name resolves to the identity's default), and a stored template — must all be associated with the tenant, or the send is refused with a 403 `AccessDeniedException` listing the missing ARNs. The send path has its own tenant-not-found wording ("Tenant \ for AwsAccountId \ not found."), reached only after the request shape validates. Not emulated: the `SendingStatus` gate (nothing can move the status off `ENABLED`) and tenant-scoped suppression filtering of sends (the account-level semantics apply). @@ -428,7 +428,7 @@ Suppressed recipients are filtered out of the SMTP relay step (non-suppressed re Export jobs render those same timelines as CSV or JSON. Floci writes the file into its own S3 emulation, under a bucket named `floci---ses-export-files`, so the presigned URL on a finished job resolves against Floci. The metrics export emits one row per dimension combination Floci has seen, where real SES emits its whole ISP catalogue with zeros, and a `RATE` is the metric's volume over the send volume for that combination. `LastEngagementEvent` filters select nothing, since Floci derives no opens or clicks. An export finishes in milliseconds, so `CancelExportJob` rarely finds a running job to catch. -Import jobs read their source from Floci's own S3 emulation, so the object has to be uploaded there rather than to real S3; the CSV and newline-delimited JSON record formats are AWS's own ([suppression list](https://docs.aws.amazon.com/ses/latest/dg/sending-email-suppression-list.html#sending-email-suppression-list-manual-add-bulk), [contact list](https://docs.aws.amazon.com/ses/latest/dg/sending-email-list-management.html#configuring-list-management-bulk-import)). A job still running when the emulator restarts is marked `FAILED` on the next start. Not emulated: `FailureInfo.FailedRecordsS3Url` (Floci writes no failed-record file), the per-file record limits, the same-region bucket rule, and `ListImportJobs` pagination, which returns every job in one page. +Import jobs read their source from Floci's own S3 emulation, so the object has to be uploaded there rather than to real S3; the CSV and newline-delimited JSON record formats are AWS's own ([suppression list](https://docs.aws.amazon.com/ses/latest/dg/sending-email-suppression-list.html#sending-email-suppression-list-manual-add-bulk), [contact list](https://docs.aws.amazon.com/ses/latest/dg/sending-email-list-management.html#configuring-list-management-bulk-import)). A job still running when the emulator restarts is marked `FAILED` on the next start. Not emulated: `FailureInfo.FailedRecordsS3Url` (Floci writes no failed-record file), the per-file record limits, and the same-region bucket rule. `SendEmail` honors `ListManagementOptions` (`ContactListName`, optional `TopicName`). When present, each recipient is matched against the named contact list and suppressed as a `Bounce` when opted out — reusing the same relay-exclusion and Bounce-event path as suppression-list filtering, matching AWS ("SES will issue a bounce event for a message that is sent to an unsubscribed contact"). A contact is opted out when `UnsubscribeAll` is set; with a `TopicName`, an explicit `OPT_OUT` preference for that topic (or, absent an explicit preference, the topic's `DefaultSubscriptionStatus` being `OPT_OUT`) suppresses; without a `TopicName`, only `UnsubscribeAll` contacts are suppressed. A recipient that is not yet a contact is created on the list automatically (as on AWS) and then evaluated. Referencing a contact list that does not exist fails the send with `NotFoundException`. The topic-default fallback at send time is an intentional deviation — it is not documented by AWS and mirrors the effective-status model AWS uses for `ListContacts`. @@ -444,6 +444,8 @@ Identity, identity-policy, template, custom-verification-template, configuration 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. +The tenant lists (`ListTenants`, `ListTenantResources`, `ListResourceTenants`) and `ListImportJobs` page the same way, within 1 to 100. The tenant lists follow real SES (probed 2026-09-25 and 2026-10-02): tenants are listed by name, a tenant's resources by ARN, and a resource's tenants in association order; the tenant or resource is looked up and the filter checked before the page size and token; a page size outside the bound and an empty `NextToken` are reported together in one Smithy validation message; and a token continues only the request it came from, so another tenant, resource or filter refuses it. Floci's own choices, where nothing could be measured: without a `PageSize` the four lists serve up to 100, and `ListImportJobs`, which refuses sandbox accounts and could not be probed at all, is modelled on the tenant lists with jobs listed oldest first. + 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). ### IAM enforcement diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesImportJobController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesImportJobController.java index db640596dd..edf1a88773 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesImportJobController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesImportJobController.java @@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.ObjectReader; 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.ImportJob; import jakarta.inject.Inject; @@ -23,8 +24,6 @@ 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.intMemberOrAbsent; import static io.github.hectorvent.floci.services.ses.SesV2Json.putTimestamp; import static io.github.hectorvent.floci.services.ses.SesV2Json.readRequiredStringField; @@ -139,14 +138,14 @@ public class SesImportJobController { String destinationType = stringMemberOrAbsent(request, "ImportDestinationType"); Integer pageSize = intMemberOrAbsent(request, "PageSize"); String nextToken = stringMemberOrAbsent(request, "NextToken"); - List jobs = importJobService.listImportJobs(region, destinationType, pageSize, nextToken); + PaginatedResult page = importJobService.listImportJobs(region, destinationType, + SesListPaging.V2_LIST_IMPORT_JOBS, pageSize, nextToken); ObjectNode result = objectMapper.createObjectNode(); ArrayNode items = result.putArray("ImportJobs"); - for (ImportJob job : jobs) { + for (ImportJob job : page.items()) { writeSummary(items.addObject(), job); } - // AWS renders NextToken as an explicit null on the last (here: only) page. - result.putNull("NextToken"); + result.put("NextToken", page.nextToken()); return Response.ok(result).build(); } catch (AwsException e) { throw remapV1Exception(e); diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesImportJobService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesImportJobService.java index ba0db710a9..bb84399dd8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesImportJobService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesImportJobService.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.ses; import com.fasterxml.jackson.core.type.TypeReference; 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.common.RequestScopes; import io.github.hectorvent.floci.core.common.Resettable; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; @@ -366,20 +367,29 @@ public class SesImportJobService implements Resettable { "Import job " + jobId + " does not exist.", 404)); } - public List listImportJobs(String region, String destinationType, Integer pageSize, - String nextToken) { + /** The filter is checked before the page size and token, and a token is bound to it, as on the tenant lists. */ + public PaginatedResult listImportJobs(String region, String destinationType, + SesListPaging paging, Integer pageSize, String nextToken) { + return paging.page(region, "/" + destinationType, listImportJobs(region, destinationType), + SesImportJobService::cursor, pageSize, nextToken); + } + + /** Oldest first, Floci's own order since SES's could not be observed; the paged list resumes on it. */ + public List listImportJobs(String region, String destinationType) { if (destinationType != null && !DESTINATION_TYPES.contains(destinationType)) { throw validationError("importDestinationType", "Member must satisfy enum value set: [SUPPRESSION_LIST, CONTACT_LIST]"); } - SesTenantService.validateListPaging(pageSize, nextToken); return importJobStore.scan(k -> k.startsWith(keyPrefix(region))).stream() .filter(j -> destinationType == null || destinationType.equals(j.getDestinationType())) - .sorted(Comparator.comparing(ImportJob::getCreatedTimestamp) - .thenComparing(ImportJob::getJobId)) + .sorted(Comparator.comparing(SesImportJobService::cursor)) .toList(); } + private static String cursor(ImportJob job) { + return SesListPaging.oldestFirst(job.getCreatedTimestamp(), job.getJobId()); + } + // ──────────────────────────── Lifecycle ──────────────────────────── // Recovery happens in the constructor, and a normal-scoped bean is only built on first use, so 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 41d30d8d02..bd34d6c211 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 @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.Pagination; import java.time.Instant; import java.util.List; +import java.util.Locale; import java.util.function.Function; /** @@ -65,7 +66,25 @@ public enum SesListPaging { 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); + true), + + /** + * The three tenant lists answer Smithy's own validation messages, reporting a bad page size and + * an empty token together, and bind a token to the request it came from (probed 2026-10-02). + * Their default page size could not be measured (it needs more than 100 tenants) and is taken + * to be the bound. + */ + V2_LIST_TENANTS(Namespace.TENANT), + + V2_LIST_TENANT_RESOURCES(Namespace.TENANT_RESOURCE), + + V2_LIST_RESOURCE_TENANTS(Namespace.RESOURCE_TENANT), + + /** + * ListImportJobs refuses sandbox accounts, so nothing about it could be probed; it is modelled + * on the tenant lists, which share its Smithy-generated validation. + */ + V2_LIST_IMPORT_JOBS(Namespace.IMPORT_JOB); private static final class Namespace { static final String TEMPLATE = "template"; @@ -73,6 +92,42 @@ public enum SesListPaging { 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"; + static final String TENANT = "tenant"; + static final String TENANT_RESOURCE = "tenant-resource"; + static final String RESOURCE_TENANT = "resource-tenant"; + static final String IMPORT_JOB = "import-job"; + } + + /** What the tenant lists share, and ListImportJobs borrows: the bound and Smithy's messages. */ + private static final class TenantLists { + static final int BOUND = 100; + static final String EMPTY_TOKEN = "Value '' at 'nextToken' failed to satisfy constraint: " + + "Member must have length greater than or equal to 1"; + + static String pageSizeViolation(int pageSize) { + String constraint = pageSize < 1 + ? "greater than or equal to 1" + : "less than or equal to " + BOUND; + return "Value '" + pageSize + "' at 'pageSize' failed to satisfy constraint: " + + "Member must have value " + constraint; + } + + static AwsException pageSizeError(int pageSize) { + return badRequest("1 validation error detected: " + pageSizeViolation(pageSize)); + } + + static AwsException tokenError(String token) { + if (token.isEmpty()) { + return badRequest("1 validation error detected: " + EMPTY_TOKEN); + } + return badRequest("Invalid Next Token"); + } + + /** SES lists the token before the page size. */ + static AwsException bothError(int pageSize) { + return badRequest("2 validation errors detected: " + EMPTY_TOKEN + "; " + + pageSizeViolation(pageSize)); + } } private final String namespace; @@ -82,22 +137,29 @@ public enum SesListPaging { private final int servedWhenOutOfRange; private final Function invalidToken; private final boolean emptyTokenInvalid; + private final Function sizeAndEmptyTokenInvalid; SesListPaging(String namespace, int defaultPageSize, int maxPageSize, Function outOfRange, Function invalidToken, boolean emptyTokenInvalid) { - this(namespace, defaultPageSize, maxPageSize, outOfRange, 0, invalidToken, emptyTokenInvalid); + this(namespace, defaultPageSize, maxPageSize, outOfRange, 0, invalidToken, emptyTokenInvalid, null); } SesListPaging(String namespace, int defaultPageSize, int maxPageSize, int servedWhenOutOfRange, Function invalidToken, boolean emptyTokenInvalid) { this(namespace, defaultPageSize, maxPageSize, null, servedWhenOutOfRange, invalidToken, - emptyTokenInvalid); + emptyTokenInvalid, null); + } + + SesListPaging(String tenantStyleNamespace) { + this(tenantStyleNamespace, TenantLists.BOUND, TenantLists.BOUND, TenantLists::pageSizeError, 0, + TenantLists::tokenError, true, TenantLists::bothError); } SesListPaging(String namespace, int defaultPageSize, int maxPageSize, Function outOfRange, int servedWhenOutOfRange, - Function invalidToken, boolean emptyTokenInvalid) { + Function invalidToken, boolean emptyTokenInvalid, + Function sizeAndEmptyTokenInvalid) { this.namespace = namespace; this.defaultPageSize = defaultPageSize; this.maxPageSize = maxPageSize; @@ -105,15 +167,31 @@ public enum SesListPaging { this.servedWhenOutOfRange = servedWhenOutOfRange; this.invalidToken = invalidToken; this.emptyTokenInvalid = emptyTokenInvalid; + this.sizeAndEmptyTokenInvalid = sizeAndEmptyTokenInvalid; } PaginatedResult page(String region, List all, Function cursorOf, Integer pageSize, String nextToken) { + return page(region, "", all, cursorOf, pageSize, nextToken); + } + + /** + * {@code scope} names what else the request selected, a tenant or a filter, for the lists whose + * tokens SES refuses once that changes. + */ + PaginatedResult page(String region, String scope, List all, Function cursorOf, + Integer pageSize, String nextToken) { + boolean emptyToken = nextToken != null && nextToken.isEmpty() && emptyTokenInvalid; + if (emptyToken && sizeAndEmptyTokenInvalid != null && pageSize != null + && (pageSize < 1 || pageSize > maxPageSize)) { + throw sizeAndEmptyTokenInvalid.apply(pageSize); + } int limit = pageSize(pageSize); - if (nextToken != null && nextToken.isEmpty() && emptyTokenInvalid) { + if (emptyToken) { throw invalidToken.apply(nextToken); } - return Pagination.paginate(all, cursorOf, limit, nextToken, namespace + "@" + region, invalidToken); + return Pagination.paginate(all, cursorOf, limit, nextToken, namespace + "@" + region + scope, + invalidToken); } int pageSize(Integer requested) { @@ -135,6 +213,18 @@ public enum SesListPaging { return descending + "#" + id; } + /** + * Oldest first, as SES lists a resource's tenants; the id orders equal timestamps. The cursor + * keeps the whole instant, so it orders exactly as a comparison of the instants does, and a + * missing timestamp sorts last. + */ + static String oldestFirst(Instant created, String id) { + String time = created == null + ? "~" + : String.format(Locale.ROOT, "%019d.%09d", created.getEpochSecond(), created.getNano()); + return time + "#" + id; + } + /** 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/SesService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java index 7dbe31c8cb..b1a935bf90 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java @@ -4,6 +4,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.AwsRegions; +import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.services.ses.model.BulkEmailEntry; import io.github.hectorvent.floci.services.ses.model.BulkEmailEntryResult; @@ -924,24 +925,25 @@ public class SesService { tenantService.disassociate(tenant, ref, region); } - public List listTenantResources(String tenantName, - String resourceTypeFilter, - Integer pageSize, String nextToken, - String region) { - SesTenantService.validateListPaging(pageSize, nextToken); - SesTenantService.validateResourceTypeFilter(resourceTypeFilter); + // Probe-confirmed order on both lists: the tenant or resource is resolved first and the filter is + // checked next, so a bad page on a missing tenant is the 404; the page size and token come last. + public PaginatedResult listTenantResources(String tenantName, + String resourceTypeFilter, + SesListPaging paging, + Integer pageSize, String nextToken, + String region) { Tenant tenant = tenantService.tenantForAssociation(tenantName, region); - return tenantService.listTenantResources(tenant, resourceTypeFilter, region); + SesTenantService.validateResourceTypeFilter(resourceTypeFilter); + return tenantService.listTenantResources(tenant, resourceTypeFilter, region, paging, pageSize, nextToken); } - public List listResourceTenants(String resourceArn, Integer pageSize, - String nextToken, String accountId, - String region) { - SesTenantService.validateListPaging(pageSize, nextToken); + public PaginatedResult listResourceTenants(String resourceArn, SesListPaging paging, + Integer pageSize, String nextToken, + String accountId, String region) { SesTenantService.AssociationResource ref = SesTenantService.parseResourceArn(resourceArn, accountId, region); requireTenantResourceExists(ref, region); - return tenantService.listResourceTenants(ref, region); + return tenantService.listResourceTenants(ref, region, paging, pageSize, nextToken); } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantController.java index e4d2c8a356..fc66f95fbb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantController.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.Tag; import io.github.hectorvent.floci.services.ses.model.Tenant; @@ -118,26 +119,31 @@ public class SesTenantController { public Response listTenants(@Context HttpHeaders headers, String body) { String region = regionResolver.resolveRegion(headers); try { - // Parse the body so a malformed request is rejected rather than silently accepted. Phase 1 - // returns every tenant in one page; PageSize/NextToken pagination is a follow-up. JsonNode request = (body == null || body.isBlank()) ? objectMapper.createObjectNode() : objectMapper.readTree(body); requireJsonObject(request); + Integer pageSize = intMemberOrAbsent(request, "PageSize"); + String nextToken = stringMemberOrAbsent(request, "NextToken"); + PaginatedResult page = tenantService.listTenants(region, SesListPaging.V2_LIST_TENANTS, + pageSize, nextToken); + ObjectNode result = objectMapper.createObjectNode(); + ArrayNode tenants = result.putArray("Tenants"); + for (Tenant t : page.items()) { + // ListTenants returns the TenantInfo subset (no Tags / SendingStatus). + ObjectNode item = tenants.addObject(); + item.put("TenantName", t.tenantName()); + item.put("TenantId", t.tenantId()); + item.put("TenantArn", t.tenantArn()); + putTimestamp(item, "CreatedTimestamp", t.createdTimestamp()); + } + result.put("NextToken", page.nextToken()); + return Response.ok(result).build(); + } catch (AwsException e) { + throw remapV1Exception(e); } catch (JsonProcessingException e) { throw new AwsException("SerializationException", null, 400); } - ObjectNode result = objectMapper.createObjectNode(); - ArrayNode tenants = result.putArray("Tenants"); - for (Tenant t : tenantService.listTenants(region)) { - // ListTenants returns the TenantInfo subset (no Tags / SendingStatus). - ObjectNode item = tenants.addObject(); - item.put("TenantName", t.tenantName()); - item.put("TenantId", t.tenantId()); - item.put("TenantArn", t.tenantArn()); - putTimestamp(item, "CreatedTimestamp", t.createdTimestamp()); - } - return Response.ok(result).build(); } @POST @@ -224,13 +230,13 @@ public class SesTenantController { } Integer pageSize = intMemberOrAbsent(request, "PageSize"); String nextToken = stringMemberOrAbsent(request, "NextToken"); - List associations = sesService.listTenantResources( - tenantName, resourceTypeFilter, pageSize, nextToken, region); + PaginatedResult page = sesService.listTenantResources( + tenantName, resourceTypeFilter, SesListPaging.V2_LIST_TENANT_RESOURCES, pageSize, nextToken, + region); ObjectNode result = objectMapper.createObjectNode(); - // AWS renders NextToken as an explicit null on the last (here: only) page. - result.putNull("NextToken"); + result.put("NextToken", page.nextToken()); ArrayNode resources = result.putArray("TenantResources"); - for (TenantResourceAssociation a : associations) { + for (TenantResourceAssociation a : page.items()) { ObjectNode item = resources.addObject(); item.put("ResourceArn", a.resourceArn()); item.put("ResourceType", a.resourceType()); @@ -255,12 +261,13 @@ public class SesTenantController { String resourceArn = stringMemberOrAbsent(request, "ResourceArn"); Integer pageSize = intMemberOrAbsent(request, "PageSize"); String nextToken = stringMemberOrAbsent(request, "NextToken"); - List associations = sesService.listResourceTenants( - resourceArn, pageSize, nextToken, regionResolver.getAccountId(), region); + PaginatedResult page = sesService.listResourceTenants( + resourceArn, SesListPaging.V2_LIST_RESOURCE_TENANTS, pageSize, nextToken, + regionResolver.getAccountId(), region); ObjectNode result = objectMapper.createObjectNode(); - result.putNull("NextToken"); + result.put("NextToken", page.nextToken()); ArrayNode tenants = result.putArray("ResourceTenants"); - for (TenantResourceAssociation a : associations) { + for (TenantResourceAssociation a : page.items()) { // ResourceTenantMetadata has no TenantArn (probe-confirmed). ObjectNode item = tenants.addObject(); item.put("TenantName", a.tenantName()); diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantService.java index 1f5831235e..1b2572e99d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesTenantService.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.Tag; @@ -133,12 +134,16 @@ public class SesTenantService { .orElseThrow(() -> tenantNotFound(tenantName)); } + public PaginatedResult listTenants(String region, SesListPaging paging, Integer pageSize, + String nextToken) { + return paging.page(region, listTenants(region), Tenant::tenantName, pageSize, nextToken); + } + + /** By name, as SES lists them; the paged list resumes on the same order. */ public List listTenants(String region) { String prefix = tenantKeyPrefix(region); return tenantStore.scan(k -> k.startsWith(prefix)).stream() - .sorted(Comparator.comparing(Tenant::createdTimestamp, - Comparator.nullsLast(Comparator.naturalOrder())) - .thenComparing(Tenant::tenantName, Comparator.nullsLast(Comparator.naturalOrder()))) + .sorted(Comparator.comparing(Tenant::tenantName)) .toList(); } @@ -413,7 +418,15 @@ public class SesTenantService { ref.arn(), tenant.tenantName(), region); } - /** AWS returns the tenant's resources ordered by ARN. */ + public PaginatedResult listTenantResources(Tenant tenant, String typeFilter, + String region, SesListPaging paging, + Integer pageSize, String nextToken) { + return paging.page(region, "/" + tenant.tenantId() + "/" + typeFilter, + listTenantResources(tenant, typeFilter, region), TenantResourceAssociation::resourceArn, + pageSize, nextToken); + } + + /** AWS returns the tenant's resources ordered by ARN; the paged list resumes on the same order. */ public List listTenantResources(Tenant tenant, String typeFilter, String region) { String prefix = associationKeyPrefix(region, tenant.tenantId()); @@ -428,7 +441,14 @@ public class SesTenantService { // itself contain the "::" delimiter (Floci barely restricts identity and template names), so a // suffix match on the key could alias one resource's associations to another's. - /** AWS returns a resource's tenants ordered by association time. */ + public PaginatedResult listResourceTenants(AssociationResource ref, String region, + SesListPaging paging, Integer pageSize, + String nextToken) { + return paging.page(region, "/" + ref.arn(), listResourceTenants(ref, region), + SesTenantService::associationCursor, pageSize, nextToken); + } + + /** AWS returns a resource's tenants ordered by association time; the paged list resumes on the same order. */ public List listResourceTenants(AssociationResource ref, String region) { String regionPrefix = "tenantAssoc::" + region + "::"; return associationStore.scan(k -> k.startsWith(regionPrefix)).stream() @@ -440,6 +460,10 @@ public class SesTenantService { .toList(); } + private static String associationCursor(TenantResourceAssociation association) { + return SesListPaging.oldestFirst(association.associatedTimestamp(), association.tenantName()); + } + /** * Finds any association for the given resource, for the facade's delete guards: AWS refuses to * delete an identity, configuration set, or template that still has tenant associations. @@ -467,21 +491,6 @@ public class SesTenantService { } } - /** - * The list operations return everything in one page, so any client-supplied NextToken is invalid — - * which is also what AWS answers for a token it cannot decrypt. PageSize is still range-checked. - */ - public static void validateListPaging(Integer pageSize, String nextToken) { - if (pageSize != null && pageSize < 1) { - throw new AwsException("BadRequestException", - "1 validation error detected: Value '" + pageSize + "' at 'pageSize' failed to " - + "satisfy constraint: Member must have value greater than or equal to 1", 400); - } - if (nextToken != null) { - throw new AwsException("BadRequestException", "Invalid Next Token", 400); - } - } - private static String associationKey(String region, String tenantId, AssociationResource ref) { return associationKeyPrefix(region, tenantId) + ref.type() + "::" + ref.name(); } diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesImportJobPagingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesImportJobPagingIntegrationTest.java new file mode 100644 index 0000000000..c6831f4ea7 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesImportJobPagingIntegrationTest.java @@ -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 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); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesImportJobServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesImportJobServiceTest.java index 2934073fe2..3a520919f7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesImportJobServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesImportJobServiceTest.java @@ -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 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 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 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 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 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 67289871e5..e33a528efb 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 @@ -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 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 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 page(SesListPaging paging, int size, String token) { return paging.page(REGION, ITEMS, Function.identity(), size, token); } diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantPagingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantPagingIntegrationTest.java new file mode 100644 index 0000000000..5c0fa3f971 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantPagingIntegrationTest.java @@ -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 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); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantServiceTest.java index a2865a41ce..7ceb28b30e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantServiceTest.java @@ -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 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 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 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 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 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 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()); } }