Light, fluffy, and always free - The AWS Local Emulator alternative
feat(ses): add the v2 reputation entity operations (#6407)
Kenshin Okinaka5a9f9cbbd6e0
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesReputationEntityTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesReputationEntityTest.javanew file mode 100644index 0000000000..79880dab53--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesReputationEntityTest.java@@ -0,0 +1,166 @@+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.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;+import software.amazon.awssdk.services.sesv2.SesV2Client;+import software.amazon.awssdk.services.sesv2.model.BadRequestException;+import software.amazon.awssdk.services.sesv2.model.ListReputationEntitiesResponse;+import software.amazon.awssdk.services.sesv2.model.NotFoundException;+import software.amazon.awssdk.services.sesv2.model.RecommendationImpact;+import software.amazon.awssdk.services.sesv2.model.ReputationEntity;+import software.amazon.awssdk.services.sesv2.model.ReputationEntityFilterKey;+import software.amazon.awssdk.services.sesv2.model.ReputationEntityType;+import software.amazon.awssdk.services.sesv2.model.SendingStatus;++import java.util.List;+import java.util.Map;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++/**+ * SDK compatibility test for the SES v2 reputation entity operations. Every tenant is an entity+ * referenced by its full ARN, which the SDK sends percent-encoded in the request path. SES reports+ * the impact of an entity without findings as {@code NONE}, a value the SDK enum does not know, so+ * the test reads it as a string.+ */+@DisplayName("SES v2 Reputation Entities")+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class SesReputationEntityTest {++ private static final String TENANT = "compat-reputation-a";+ private static final String OTHER_TENANT = "compat-reputation-b";++ private static SesV2Client sesV2;+ private static String tenantArn;+ private static String otherTenantArn;++ @BeforeAll+ static void setup() {+ sesV2 = TestFixtures.sesV2Client();+ tenantArn = sesV2.createTenant(r -> r.tenantName(TENANT)).tenantArn();+ otherTenantArn = sesV2.createTenant(r -> r.tenantName(OTHER_TENANT)).tenantArn();+ }++ @AfterAll+ static void cleanup() {+ if (sesV2 == null) {+ return;+ }+ for (String name : List.of(TENANT, OTHER_TENANT)) {+ try {+ sesV2.deleteTenant(r -> r.tenantName(name));+ } catch (NotFoundException expected) {+ // Already removed by the delete test; anything else (auth, connectivity) must surface.+ }+ }+ }++ @Test+ @Order(1)+ @DisplayName("ListReputationEntities includes the tenant with its defaults")+ void listIncludesTenant() {+ ListReputationEntitiesResponse response = sesV2.listReputationEntities(r -> r+ .filter(Map.of(ReputationEntityFilterKey.ENTITY_REFERENCE_PREFIX, tenantArn)));++ assertThat(response.reputationEntities()).hasSize(1);+ ReputationEntity entity = response.reputationEntities().get(0);+ assertThat(entity.reputationEntityReference()).isEqualTo(tenantArn);+ assertThat(entity.reputationEntityType()).isEqualTo(ReputationEntityType.RESOURCE);+ assertThat(entity.reputationImpact()).isEqualTo(RecommendationImpact.UNKNOWN_TO_SDK_VERSION);+ assertThat(entity.reputationImpactAsString()).isEqualTo("NONE");+ assertThat(entity.reputationManagementPolicy()).endsWith(":aws:reputation-policy/standard");+ assertThat(entity.customerManagedStatus()).isNull();+ assertThat(entity.sendingStatusAggregate()).isEqualTo(SendingStatus.ENABLED);+ assertThat(response.nextToken()).isNull();+ }++ @Test+ @Order(2)+ @DisplayName("The paginator walks the entities a page at a time")+ void paginatesEntities() {+ String prefix = tenantArn.substring(0, tenantArn.indexOf(TENANT));++ List<String> references = sesV2.listReputationEntitiesPaginator(r -> r+ .filter(Map.of(ReputationEntityFilterKey.ENTITY_REFERENCE_PREFIX, prefix + "compat-reputation-"))+ .pageSize(1))+ .reputationEntities().stream()+ .map(ReputationEntity::reputationEntityReference)+ .toList();++ assertThat(references).containsExactly(tenantArn, otherTenantArn);+ }++ @Test+ @Order(3)+ @DisplayName("UpdateReputationEntityPolicy changes the policy GetReputationEntity reports")+ void updatePolicy() {+ String strict = sesV2.getReputationEntity(r -> r.reputationEntityType(ReputationEntityType.RESOURCE)+ .reputationEntityReference(tenantArn))+ .reputationEntity().reputationManagementPolicy().replace("/standard", "/strict");++ sesV2.updateReputationEntityPolicy(r -> r.reputationEntityType(ReputationEntityType.RESOURCE)+ .reputationEntityReference(tenantArn).reputationEntityPolicy(strict));++ assertThat(sesV2.getReputationEntity(r -> r.reputationEntityType(ReputationEntityType.RESOURCE)+ .reputationEntityReference(tenantArn))+ .reputationEntity().reputationManagementPolicy()).isEqualTo(strict);+ }++ @Test+ @Order(4)+ @DisplayName("A DISABLED customer-managed status becomes the aggregate and the tenant's status")+ void disableSending() {+ sesV2.updateReputationEntityCustomerManagedStatus(r -> r+ .reputationEntityType(ReputationEntityType.RESOURCE)+ .reputationEntityReference(tenantArn)+ .sendingStatus(SendingStatus.DISABLED));++ ReputationEntity entity = sesV2.getReputationEntity(r -> r+ .reputationEntityType(ReputationEntityType.RESOURCE)+ .reputationEntityReference(tenantArn)).reputationEntity();+ assertThat(entity.customerManagedStatus().status()).isEqualTo(SendingStatus.DISABLED);+ assertThat(entity.customerManagedStatus().cause()).isEqualTo("Status manually updated.");+ assertThat(entity.customerManagedStatus().lastUpdatedTimestamp()).isNotNull();+ assertThat(entity.awsSesManagedStatus()).isNull();+ assertThat(entity.sendingStatusAggregate()).isEqualTo(SendingStatus.DISABLED);+ assertThat(sesV2.getTenant(r -> r.tenantName(TENANT)).tenant().sendingStatus())+ .isEqualTo(SendingStatus.DISABLED);+ assertThat(sesV2.listReputationEntities(r -> r+ .filter(Map.of(ReputationEntityFilterKey.SENDING_STATUS, SendingStatus.DISABLED.toString())))+ .reputationEntities())+ .extracting(ReputationEntity::reputationEntityReference)+ .contains(tenantArn)+ .doesNotContain(otherTenantArn);+ }++ @Test+ @Order(5)+ @DisplayName("An ARN that names no tenant is a BadRequestException")+ void unknownEntity() {+ String ghost = tenantArn.substring(0, tenantArn.lastIndexOf('/') + 1) + "tn-000000000000000000000000000000";++ assertThatThrownBy(() -> sesV2.getReputationEntity(r -> r+ .reputationEntityType(ReputationEntityType.RESOURCE)+ .reputationEntityReference(ghost)))+ .isInstanceOf(BadRequestException.class)+ .hasMessageContaining("ReputationEntity <" + ghost + "> does not exist");+ }++ @Test+ @Order(6)+ @DisplayName("Deleting the tenant removes the entity")+ void deleteTenantRemovesEntity() {+ sesV2.deleteTenant(r -> r.tenantName(TENANT));++ assertThatThrownBy(() -> sesV2.getReputationEntity(r -> r+ .reputationEntityType(ReputationEntityType.RESOURCE)+ .reputationEntityReference(tenantArn)))+ .isInstanceOf(BadRequestException.class);+ }+}diff --git a/docs/services/ses.md b/docs/services/ses.mdindex 82fbe58e07..e84a88b638 100644--- a/docs/services/ses.md+++ b/docs/services/ses.md@@ -420,6 +420,10 @@ Alongside the classic Query API, Floci implements a subset of the SES v2 REST JS| `POST` | `/v2/email/identity/certificates` | `AssociateEmailIdentityCertificate` || `POST` | `/v2/email/identity/certificates/delete` | `DisassociateEmailIdentityCertificate` || `POST` | `/v2/email/identity/certificates/list` | `ListEmailIdentityCertificates` |+| `POST` | `/v2/email/reputation/entities` | `ListReputationEntities` |+| `GET` | `/v2/email/reputation/entities/{ReputationEntityType}/{ReputationEntityReference}` | `GetReputationEntity` |+| `PUT` | `/v2/email/reputation/entities/{ReputationEntityType}/{ReputationEntityReference}/policy` | `UpdateReputationEntityPolicy` |+| `PUT` | `/v2/email/reputation/entities/{ReputationEntityType}/{ReputationEntityReference}/customer-managed-status` | `UpdateReputationEntityCustomerManagedStatus` |Floci models no leased dedicated IPs: `GetDedicatedIps` is empty and IP-targeted operations return `NotFoundException`, as real AWS does for an account with no leased IPs, with required request members validated first (`BadRequestException`). `PutDedicatedIpPoolScalingAttributes` rejects downgrading a `MANAGED` pool to `STANDARD`, and `PutAccountDedicatedIpWarmupAttributes` stores the flag behind `GetAccount.DedicatedIpAutoWarmupEnabled` (default `true`).@@ -453,10 +457,12 @@ Tenants (multi-tenancy) are stored per region. `CreateTenant` requires a `TenantTenant 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 \<name\> for AwsAccountId \<account\> 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).+A `TenantName` on `SendEmail`/`SendBulkEmail` makes the send tenant-scoped. Every resource it uses must be associated with the tenant: 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. Otherwise the send is refused with a 403 `AccessDeniedException` listing the missing ARNs. The send path has its own tenant-not-found wording ("Tenant \<name\> for AwsAccountId \<account\> not found."), reached only after the request shape validates. A tenant whose sending status is `DISABLED` is refused with a 400 `MessageRejected` before identity verification, the association check and a raw message's missing recipients. As on SES, a malformed address, a Simple or Template send with no recipient, and an unknown configuration set named by a `SendEmail` request are reported first; `SendBulkEmail` refuses the tenant before it looks up the configuration set. `SendBulkEmail` looks the tenant up before an unknown stored template, and skips the tenant checks altogether when no entry names a recipient: every entry then answers `Destination cannot be empty`, as it does without a tenant. Not emulated: tenant-scoped suppression filtering of sends (the account-level semantics apply).`PutTenantSuppressionAttributes` sets a tenant's `SuppressedReasons`/`SuppressionScope` pair on AWS's own singular `/v2/email/tenant/suppression` route. The pair is all-or-nothing: both members set the block (an empty reason list is valid), half a pair is rejected, and a bare `TenantName` clears it. A `TenantName` on the suppression-list operations (body member on put, query parameter on get/delete/list) routes them to the tenant's own list — separate from the account list, independent of `SuppressionScope`, cascaded away by `DeleteTenant`, and with a non-idempotent delete.+Every tenant is a [reputation entity](https://docs.aws.amazon.com/ses/latest/dg/tenants.html#configuring-reputation-policies) of type `RESOURCE`, referenced by its full ARN (`tenant/<name>/<id>`). As on SES, the `tenant/<id>` form shown in the AWS CLI examples names no entity. Floci keeps no reputation findings, so `ReputationImpact` is always `NONE` (a value the SDK enums do not list, as on SES) and `AwsSesManagedStatus` is always null: the customer-managed status set by `UpdateReputationEntityCustomerManagedStatus` is the `SendingStatusAggregate`, which `GetTenant` reports as the tenant's `SendingStatus` and the `ListTenants` `SENDING_STATUS` filter matches at once, where the SES filter catches up after several seconds. A new tenant has the Standard policy, and nothing pauses a tenant automatically. `UpdateReputationEntityPolicy` accepts the `standard`, `strict` and `none` SES-managed policy ARNs and stores the one given; as on SES, their partition and region are not checked. Every error is a 400 `BadRequestException`, an unknown entity included, matching real SES (probed 2026-10-23). `ListReputationEntities` lists entities by ARN, takes one `Filter` key at a time and binds its token to that filter; without a `PageSize` it serves up to 1000, since no default could be measured.+Suppression list entries are stored per region with `Reason` ∈ {`BOUNCE`, `COMPLAINT`}. At send time, a recipient is suppressed when it appears on the suppression list AND its stored `Reason` is contained in the **effective** `SuppressedReasons` for the send. The effective list is the configuration set's `SuppressionOptions.SuppressedReasons` (set via `PutConfigurationSetSuppressionOptions`) when present — an **empty list is preserved as an explicit "no suppression filtering for this configuration set"** — otherwise it falls back to the account-level `AccountSuppressionAttributes.SuppressedReasons` (set via `PutAccountSuppressionAttributes`, default `[BOUNCE, COMPLAINT]`). Following the AWS V2 contract, there is no dedicated `GetConfigurationSetSuppressionOptions` action; once set, the block is read back through `GetConfigurationSet`'s response (the field is omitted when the configuration set has no override).Suppressed recipients are filtered out of the SMTP relay step (non-suppressed recipients on the same send still reach the relay normally), and the configuration set's event destinations receive a synthetic `Bounce` or `Complaint` event alongside the always-emitted `Send` event. The `SendEmail` API response (`200` + `MessageId`), the stored `SentEmail` visible at `GET /_aws/ses`, and the published event's `mail.destination` all retain the original recipient list — matching the AWS contract that the message is "accepted, just not sent" for suppressed addresses.@@ -505,7 +511,7 @@ S/MIME certificate associations are stored per region and never used: Floci does### Request member types-The operations whose body nests a structure in a structure, or holds a list of structures, check the request body against the SES v2 service model before anything else is validated, as AWS's restJson1 deserializer does: the send operations (`SendEmail`, `SendBulkEmail`, `SendCustomVerificationEmail`), `CreateConfigurationSet`, `UpdateConfigurationSet`, `PutConfigurationSetSuppressionOptions`, `PutConfigurationSetVdmOptions`, `CreateConfigurationSetEventDestination`, `UpdateConfigurationSetEventDestination`, `CreateContactList`, `UpdateContactList`, `CreateContact`, `UpdateContact`, `ListContacts`, `PutAccountSuppressionAttributes`, `PutAccountVdmAttributes`, `BatchGetMetricData`, `CreateImportJob` and `CreateExportJob`. In those operations, the first body member of the wrong JSON type, in body order, is a `SerializationException` with AWS's deserializer message:+The operations whose body nests a structure in a structure, or holds a list of structures, check the request body against the SES v2 service model before anything else is validated, as AWS's restJson1 deserializer does: the send operations (`SendEmail`, `SendBulkEmail`, `SendCustomVerificationEmail`), `CreateConfigurationSet`, `UpdateConfigurationSet`, `PutConfigurationSetSuppressionOptions`, `PutConfigurationSetVdmOptions`, `CreateConfigurationSetEventDestination`, `UpdateConfigurationSetEventDestination`, `CreateContactList`, `UpdateContactList`, `CreateContact`, `UpdateContact`, `ListContacts`, `PutAccountSuppressionAttributes`, `PutAccountVdmAttributes`, `BatchGetMetricData`, `CreateImportJob` and `CreateExportJob`. `ListReputationEntities`, `UpdateReputationEntityPolicy` and `UpdateReputationEntityCustomerManagedStatus` run the same check although their bodies are flat. In those operations, the first body member of the wrong JSON type, in body order, is a `SerializationException` with AWS's deserializer message:| Member type | Value sent | Message ||---|---|---|@@ -515,7 +521,7 @@ The operations whose body nests a structure in a structure, or holds a list of s| map | array / any other non-object | `Start of list found where not expected` / `Expected map or null` || list | object / any other non-array | `Start of structure or map found where not expected.` / `Expected list or null` |-A JSON `null` member counts as absent. A `null` address list element passes this check and fails later, as on AWS: `SendEmail` answers `Invalid email address null.` after its content and sender checks and before the tenant lookup, and `SendBulkEmail` reports it as the `INVALID_PARAMETER` status of the entry it belongs to (of every entry for a `null` Reply-To), or as `Destination cannot be empty` when no entry of the request has a non-null recipient. A `null` element of `Topics` (`CreateContactList`, `UpdateContactList`) or `TopicPreferences` (`CreateContact`, `UpdateContact`) also passes this check, but there AWS answers it with a `500 InternalFailure`, which Floci replaces with `BadRequestException` naming the element ("1 validation error detected: Value at 'topics.1.member.topicName' failed to satisfy constraint: Member must not be null"). The account-level sending switch is still checked first, so a paused account answers `SendingPausedException` even for a malformed body. Likewise `BatchGetMetricData` checks that Virtual Deliverability Manager is enabled before it reads the body.+A JSON `null` member counts as absent. A `null` address list element passes this check and fails later, as on AWS: `SendEmail` answers `Invalid email address null.` after its content and sender checks and before the tenant lookup, and `SendBulkEmail` reports it as the `INVALID_PARAMETER` status of the entry it belongs to (of every entry for a `null` Reply-To), or as `Destination cannot be empty` when no entry of the request has a non-null recipient, the answer every entry gets then, whatever its lists hold. A `null` element of `Topics` (`CreateContactList`, `UpdateContactList`) or `TopicPreferences` (`CreateContact`, `UpdateContact`) also passes this check, but there AWS answers it with a `500 InternalFailure`, which Floci replaces with `BadRequestException` naming the element ("1 validation error detected: Value at 'topics.1.member.topicName' failed to satisfy constraint: Member must not be null"). The account-level sending switch is still checked first, so a paused account answers `SendingPausedException` even for a malformed body. Likewise `BatchGetMetricData` checks that Virtual Deliverability Manager is enabled before it reads the body.The other operations check their members one at a time, and some of them still answer a wrong JSON type with `BadRequestException`. The list operations' map `Filter` answers as in the table. Their integer `PageSize`, like `CreateExportJob`'s `MaxResults`, answers a string with `STRING_VALUE can not be converted to an Integer` (`TRUE_VALUE` / `FALSE_VALUE` for a boolean, and as in the table for an object or an array), while a number is read as an int first, as on AWS: `1.5` is accepted, and a value above the int range is checked against the page-size bounds as `2147483647`.diff --git a/src/main/java/io/github/hectorvent/floci/core/common/Pagination.java b/src/main/java/io/github/hectorvent/floci/core/common/Pagination.javaindex acc091b7fd..564d8cae14 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/Pagination.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/Pagination.java@@ -112,6 +112,21 @@ public final class Pagination {}}+ /**+ * True when {@code token} decodes to a cursor that starts with {@code prefix}, for callers that+ * need to tell a token they issued under another scope from one that is not theirs at all.+ */+ public static boolean tokenStartsWith(String token, String prefix) {+ if (token == null || token.isEmpty()) {+ return false;+ }+ try {+ return new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8).startsWith(prefix);+ } catch (IllegalArgumentException e) {+ return false;+ }+ }+private static String encodeToken(String cursor) {return Base64Url.encode(cursor);}diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.javaindex 14e23b917c..a72dc18aeb 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java@@ -78,6 +78,7 @@ import io.github.hectorvent.floci.services.ses.SesIdentityController;import io.github.hectorvent.floci.services.ses.SesImportJobController;import io.github.hectorvent.floci.services.ses.SesInsightsController;import io.github.hectorvent.floci.services.ses.SesMetricsController;+import io.github.hectorvent.floci.services.ses.SesReputationEntityController;import io.github.hectorvent.floci.services.ses.SesSendController;import io.github.hectorvent.floci.services.ses.SesSuppressionController;import io.github.hectorvent.floci.services.ses.SesTagController;@@ -338,7 +339,7 @@ public class ResolvedServiceCatalog {SesDedicatedIpController.class, SesExportJobController.class,SesIdentityController.class,SesInsightsController.class, SesMetricsController.class,- SesSendController.class,+ SesReputationEntityController.class, SesSendController.class,SesSuppressionController.class, SesTagController.class,SesTemplateController.class, SesImportJobController.class,SesTenantController.class)),diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesListPaging.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesListPaging.javaindex dfac2f5d48..dc14ffa624 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@@ -137,6 +137,16 @@ public enum SesListPaging {token -> new AwsException("InvalidNextTokenException", "Token is invalid.", 400),true),+ /**+ * ListReputationEntities (probed 2026-10-23): an empty token is refused like an unreadable one,+ * and a token from another filter has its own message, which the service renders. Three entities+ * came back whole without a PageSize, so the default is taken to be the bound.+ */+ V2_LIST_REPUTATION_ENTITIES(Namespace.REPUTATION_ENTITY, 1000, 1000,+ size -> badRequest("The page size must be between 1 and 1000"),+ token -> badRequest("Failed to deserialize token. "),+ true),+/*** The request has no size member; the model documents "up to 100 receipt rule sets at a time".* SES allows 40 rule sets per region, so a second page could not be observed.@@ -162,6 +172,7 @@ public enum SesListPaging {static final String DEDICATED_IP = "dedicated-ip";static final String SUPPRESSED_DESTINATION = "suppressed-destination";static final String RECEIPT_RULE_SET = "receipt-rule-set";+ static final String REPUTATION_ENTITY = "reputation-entity";}/** What the tenant lists share, and ListImportJobs borrows: the bound and Smithy's messages. */@@ -273,6 +284,16 @@ public enum SesListPaging {return limit;}+ /**+ * True when {@code token} is one this list issued in {@code region}, whatever it was bound to, so+ * a list whose tokens SES refuses with a message of their own once the filter changes can tell+ * that case from an unreadable token.+ */+ boolean issuedInRegion(String token, String region) {+ String issuer = namespace + "@" + region;+ return Pagination.tokenStartsWith(token, issuer + ":") || Pagination.tokenStartsWith(token, issuer + "#");+ }+int pageSize(Integer requested) {if (requested == null) {return defaultPageSize;diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesReputationEntityController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesReputationEntityController.javanew file mode 100644index 0000000000..ad7531e895--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesReputationEntityController.java@@ -0,0 +1,138 @@+package io.github.hectorvent.floci.services.ses;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ArrayNode;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.PaginatedResult;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.services.ses.SesReputationEntityService.ReputationEntity;+import io.github.hectorvent.floci.services.ses.model.ReputationStatusRecord;+import jakarta.inject.Inject;+import jakarta.ws.rs.Consumes;+import jakarta.ws.rs.GET;+import jakarta.ws.rs.POST;+import jakarta.ws.rs.PUT;+import jakarta.ws.rs.Path;+import jakarta.ws.rs.PathParam;+import jakarta.ws.rs.Produces;+import jakarta.ws.rs.core.Context;+import jakarta.ws.rs.core.HttpHeaders;+import jakarta.ws.rs.core.MediaType;+import jakarta.ws.rs.core.Response;++import java.util.List;+import java.util.Map;++import static io.github.hectorvent.floci.services.ses.SesV2Json.filterValues;+import static io.github.hectorvent.floci.services.ses.SesV2Json.intMemberOrAbsent;+import static io.github.hectorvent.floci.services.ses.SesV2Json.putTimestamp;+import static io.github.hectorvent.floci.services.ses.SesV2Json.readOptionBody;+import static io.github.hectorvent.floci.services.ses.SesV2Json.stringMapMemberOrAbsent;+import static io.github.hectorvent.floci.services.ses.SesV2Json.stringMemberOrAbsent;++/**+ * SES V2 reputation entity endpoints ({@code /v2/email/reputation/entities}). The reference is an+ * ARN, which the SDKs send percent-encoded as one path segment. The router matches the encoded+ * path, so the reference stays one segment there and is decoded only as a parameter; a reference+ * sent with literal slashes reaches no route, as on SES, and so cannot pass the IAM route rules+ * as an unknown action.+ */+@Path("/v2/email/reputation/entities")+@Produces(MediaType.APPLICATION_JSON)+@Consumes(MediaType.APPLICATION_JSON)+public class SesReputationEntityController {++ /** In the order SES prints them when it refuses a key. */+ private static final List<String> FILTER_KEYS =+ List.of("ENTITY_REFERENCE_PREFIX", "REPUTATION_IMPACT", "ENTITY_TYPE", "SENDING_STATUS");+ private static final int FILTER_VALUE_MAX = 512;++ private final SesReputationEntityService reputationService;+ private final RegionResolver regionResolver;+ private final ObjectMapper objectMapper;++ @Inject+ public SesReputationEntityController(SesReputationEntityService reputationService,+ RegionResolver regionResolver, ObjectMapper objectMapper) {+ this.reputationService = reputationService;+ this.regionResolver = regionResolver;+ this.objectMapper = objectMapper;+ }++ @POST+ public Response listReputationEntities(@Context HttpHeaders headers, String body) {+ String region = regionResolver.resolveRegion(headers);+ JsonNode request = readOptionBody(objectMapper, body);+ SesV2RequestShapes.check("ListReputationEntities", request);+ Map<String, String> filter = filterValues(stringMapMemberOrAbsent(request, "Filter"), FILTER_KEYS,+ FILTER_VALUE_MAX);+ Integer pageSize = intMemberOrAbsent(request, "PageSize");+ String nextToken = stringMemberOrAbsent(request, "NextToken");+ PaginatedResult<ReputationEntity> page = reputationService.list(filter, pageSize, nextToken, region);+ ObjectNode result = objectMapper.createObjectNode();+ result.put("NextToken", page.nextToken());+ ArrayNode entities = result.putArray("ReputationEntities");+ for (ReputationEntity entity : page.items()) {+ entities.add(entityJson(entity));+ }+ return Response.ok(result).build();+ }++ @GET+ @Path("/{type}/{reference}")+ public Response getReputationEntity(@Context HttpHeaders headers, @PathParam("type") String type,+ @PathParam("reference") String reference) {+ String region = regionResolver.resolveRegion(headers);+ ObjectNode result = objectMapper.createObjectNode();+ result.set("ReputationEntity", entityJson(reputationService.get(type, reference, region)));+ return Response.ok(result).build();+ }++ @PUT+ @Path("/{type}/{reference}/policy")+ public Response updateReputationEntityPolicy(@Context HttpHeaders headers, @PathParam("type") String type,+ @PathParam("reference") String reference, String body) {+ String region = regionResolver.resolveRegion(headers);+ JsonNode request = readOptionBody(objectMapper, body);+ SesV2RequestShapes.check("UpdateReputationEntityPolicy", request);+ String policy = stringMemberOrAbsent(request, "ReputationEntityPolicy");+ reputationService.updatePolicy(type, reference, policy, region);+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ @PUT+ @Path("/{type}/{reference}/customer-managed-status")+ public Response updateReputationEntityCustomerManagedStatus(@Context HttpHeaders headers,+ @PathParam("type") String type,+ @PathParam("reference") String reference,+ String body) {+ String region = regionResolver.resolveRegion(headers);+ JsonNode request = readOptionBody(objectMapper, body);+ SesV2RequestShapes.check("UpdateReputationEntityCustomerManagedStatus", request);+ String status = stringMemberOrAbsent(request, "SendingStatus");+ reputationService.updateCustomerManagedStatus(type, reference, status, region);+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ /** SES renders every member, an unset one as an explicit null. */+ private ObjectNode entityJson(ReputationEntity entity) {+ ObjectNode node = objectMapper.createObjectNode();+ node.putNull("AwsSesManagedStatus");+ ReputationStatusRecord status = entity.customerManagedStatus();+ if (status == null) {+ node.putNull("CustomerManagedStatus");+ } else {+ ObjectNode record = node.putObject("CustomerManagedStatus");+ record.put("Cause", status.cause());+ putTimestamp(record, "LastUpdatedTimestamp", status.lastUpdatedTimestamp());+ record.put("Status", status.status());+ }+ node.put("ReputationEntityReference", entity.reference());+ node.put("ReputationEntityType", SesReputationEntityService.ENTITY_TYPE);+ node.put("ReputationImpact", SesReputationEntityService.NO_IMPACT);+ node.put("ReputationManagementPolicy", entity.policy());+ node.put("SendingStatusAggregate", entity.sendingStatusAggregate());+ return node;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesReputationEntityService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesReputationEntityService.javanew file mode 100644index 0000000000..5828c52a28--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesReputationEntityService.java@@ -0,0 +1,199 @@+package io.github.hectorvent.floci.services.ses;++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.common.SmithyValidationErrors;+import io.github.hectorvent.floci.services.ses.model.ReputationStatusRecord;+import io.github.hectorvent.floci.services.ses.model.Tenant;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.time.Clock;+import java.time.Instant;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.function.Predicate;++/**+ * SES v2 reputation entities. SES makes every tenant one, of type {@code RESOURCE}, referenced by+ * the tenant's full ARN, so the state lives on the {@link Tenant} record in+ * {@link SesTenantService}; this service validates the requests and derives the entity view.+ *+ * <p>Behaviour probe-confirmed against real SES (us-west-2, 2026-10-23): every error is a 400+ * {@code BadRequestException}, an unknown entity included. Floci has no reputation findings, so+ * the impact is always {@code NONE} and SES never manages a status of its own: the customer-managed+ * status is the aggregate.+ */+@ApplicationScoped+public class SesReputationEntityService {++ private static final Logger LOG = Logger.getLogger(SesReputationEntityService.class);++ static final String ENTITY_TYPE = "RESOURCE";+ static final String NO_IMPACT = "NONE";+ private static final String DEFAULT_POLICY = "standard";+ private static final Set<String> POLICIES = Set.of("standard", "strict", "none");+ private static final String POLICY_PREFIX = "reputation-policy/";+ private static final String POLICY_ACCOUNT = "aws"; // partition-literal: the account SES-managed policies belong to+ private static final List<String> SENDING_STATUSES = List.of("ENABLED", "REINSTATED", "DISABLED");+ // SES refuses any other impact, but MEDIUM is accepted as a filter although no entity carries it.+ private static final Set<String> IMPACTS = Set.of("NONE", "LOW", "MEDIUM", "HIGH");+ private static final String MANUAL_CAUSE = "Status manually updated.";++ /** A tenant seen as a reputation entity. */+ record ReputationEntity(String reference, String policy, ReputationStatusRecord customerManagedStatus,+ String sendingStatusAggregate) {+ }++ private final SesTenantService tenantService;+ private final Clock clock;++ @Inject+ public SesReputationEntityService(SesTenantService tenantService, Clock clock) {+ this.tenantService = tenantService;+ this.clock = clock;+ }++ public ReputationEntity get(String type, String reference, String region) {+ requireType(type);+ requireReference(reference);+ return tenantService.findByArn(reference, region)+ .map(t -> entity(t, region))+ .orElseThrow(() -> entityNotFound(reference));+ }++ /**+ * SES checks the policy before anything else, the entity type included, and answers a missing+ * or unknown policy as it answers a reference that is not an ARN. Only the account and the+ * resource are checked: a policy of any partition or region, even a blank or unknown one, is+ * accepted and stored as given.+ */+ public void updatePolicy(String type, String reference, String policy, String region) {+ requirePolicy(policy);+ requireType(type);+ requireReference(reference);+ tenantService.updateByArn(reference, region, t -> t.withReputationPolicy(policy))+ .orElseThrow(() -> entityNotFound(reference));+ LOG.infov("Set reputation policy {0} on SES tenant {1}", policy, reference);+ }++ /** Setting the status it already has is accepted, and still refreshes the timestamp. */+ public void updateCustomerManagedStatus(String type, String reference, String status, String region) {+ requireType(type);+ requireReference(reference);+ if (status == null) {+ throw SmithyValidationErrors.badRequest(+ "Value at 'sendingStatus' failed to satisfy constraint: Member must not be null");+ }+ if (!SENDING_STATUSES.contains(status)) {+ throw SmithyValidationErrors.badRequest("Value at 'sendingStatus' failed to satisfy constraint: "+ + "Member must satisfy enum value set: [" + String.join(", ", SENDING_STATUSES) + "]");+ }+ ReputationStatusRecord record = new ReputationStatusRecord(status, MANUAL_CAUSE, Instant.now(clock));+ tenantService.updateByArn(reference, region, t -> t.withCustomerManagedStatus(record))+ .orElseThrow(() -> entityNotFound(reference));+ LOG.infov("Set customer-managed sending status {0} on SES tenant {1}", status, reference);+ }++ /**+ * SES checks the page size and an empty token first, then the filter, then the token. The filter+ * holds one key at most, its values are case-sensitive, and a token is bound to the filter it+ * came from. Entities are listed by reference.+ */+ public PaginatedResult<ReputationEntity> list(Map<String, String> filter, Integer pageSize, String nextToken,+ String region) {+ SesListPaging paging = SesListPaging.V2_LIST_REPUTATION_ENTITIES;+ paging.checkRequest(pageSize, nextToken);+ if (filter.size() > 1) {+ throw new AwsException("BadRequestException", "Too many filters provided.", 400);+ }+ Map.Entry<String, String> only = filter.isEmpty() ? null : filter.entrySet().iterator().next();+ Predicate<ReputationEntity> matches = filterPredicate(only);+ List<ReputationEntity> entities = tenantService.listTenants(region).stream()+ .map(t -> entity(t, region))+ .filter(matches)+ .toList();+ String scope = only == null ? "" : only.getKey() + "=" + only.getValue();+ try {+ return paging.page(region, scope, entities, ReputationEntity::reference, pageSize, nextToken);+ } catch (AwsException e) {+ if (paging.issuedInRegion(nextToken, region)) {+ throw new AwsException("BadRequestException",+ "Pagination token is bound to a different set of filtering parameters", 400);+ }+ throw e;+ }+ }++ private static Predicate<ReputationEntity> filterPredicate(Map.Entry<String, String> entry) {+ if (entry == null) {+ return e -> true;+ }+ String value = entry.getValue();+ return switch (entry.getKey()) {+ case "SENDING_STATUS" -> {+ requireFilterValue(entry.getKey(), SENDING_STATUSES.contains(value));+ yield e -> value.equals(e.sendingStatusAggregate());+ }+ case "ENTITY_TYPE" -> {+ requireFilterValue(entry.getKey(), ENTITY_TYPE.equals(value));+ yield e -> true;+ }+ case "REPUTATION_IMPACT" -> {+ requireFilterValue(entry.getKey(), IMPACTS.contains(value));+ yield e -> NO_IMPACT.equals(value);+ }+ default -> e -> e.reference().startsWith(value);+ };+ }++ private static void requireFilterValue(String key, boolean valid) {+ if (!valid) {+ throw new AwsException("BadRequestException", "Invalid reputation entity " + key + " specified", 400);+ }+ }++ private static ReputationEntity entity(Tenant tenant, String region) {+ String policy = tenant.reputationPolicy() != null+ ? tenant.reputationPolicy()+ : AwsArnUtils.Arn.of("ses", region, POLICY_ACCOUNT, POLICY_PREFIX + DEFAULT_POLICY).toString();+ return new ReputationEntity(tenant.tenantArn(), policy, tenant.customerManagedStatus(),+ tenant.sendingStatus());+ }++ private static void requireType(String type) {+ if (!ENTITY_TYPE.equals(type)) {+ throw SmithyValidationErrors.badRequest("Value at 'reputationEntityType' failed to satisfy "+ + "constraint: Member must satisfy enum value set: [" + ENTITY_TYPE + "]");+ }+ }++ private static void requireReference(String reference) {+ if (!AwsArnUtils.isArnFor(reference, "ses")) {+ throw invalidIdentifier();+ }+ }++ private static void requirePolicy(String policy) {+ if (!AwsArnUtils.isArnFor(policy, "ses")) {+ throw invalidIdentifier();+ }+ AwsArnUtils.Arn arn = AwsArnUtils.parse(policy);+ if (!POLICY_ACCOUNT.equals(arn.accountId())+ || !arn.resource().startsWith(POLICY_PREFIX)+ || !POLICIES.contains(arn.resource().substring(POLICY_PREFIX.length()))) {+ throw invalidIdentifier();+ }+ }++ private static AwsException invalidIdentifier() {+ return new AwsException("BadRequestException", "Provided resource identifier is invalid", 400);+ }++ private static AwsException entityNotFound(String reference) {+ return new AwsException("BadRequestException", "ReputationEntity <" + reference + "> does not exist", 400);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesSendController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesSendController.javaindex 93a48bf504..2d77d7eb36 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesSendController.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesSendController.java@@ -160,12 +160,12 @@ public class SesSendController {List<MessageAttachment> attachments =parseAttachmentsArray(simple.path("Attachments"), "content.simple.attachments");requireNoNullAddress(toAddresses, ccAddresses, bccAddresses, replyToAddresses);- sesService.checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName,- null, regionResolver.getAccountId(), region);- messageId = sesService.sendEmail(sendRequest+ SendEmailRequest simpleRequest = sendRequest.content(new EmailContent.Simple(subject, bodyText, bodyHtml, additionalHeaders,attachments))- .build());+ .build();+ sesService.checkTenantSendAccess(simpleRequest, null, regionResolver.getAccountId());+ messageId = sesService.sendEmail(simpleRequest);} else if (content.has("Template")) {if (fromEmailAddress == null || fromEmailAddress.isBlank()) {throw new AwsException("BadRequestException", "Source cannot be empty", 400);@@ -194,11 +194,11 @@ public class SesSendController {? templateName: SesTemplateService.templateNameFromArn(templateArn);requireNoNullAddress(toAddresses, ccAddresses, bccAddresses, replyToAddresses);- sesService.checkTenantSendAccess(tenantName, fromEmailAddress,- configurationSetName, resolvedName, regionResolver.getAccountId(), region);- messageId = sesService.sendEmail(sendRequest+ SendEmailRequest templateRequest = sendRequest.content(new EmailContent.Template(resolvedName, templateData, additionalHeaders))- .build());+ .build();+ sesService.checkTenantSendAccess(templateRequest, resolvedName, regionResolver.getAccountId());+ messageId = sesService.sendEmail(templateRequest);} else {JsonNode inline = template.path("TemplateContent");String subject = inline.path("Subject").asText(null);@@ -209,12 +209,12 @@ public class SesSendController {// configuration set pass through the gate.SesService.requireInlineTemplateContent(subject, text, html);requireNoNullAddress(toAddresses, ccAddresses, bccAddresses, replyToAddresses);- sesService.checkTenantSendAccess(tenantName, fromEmailAddress,- configurationSetName, null, regionResolver.getAccountId(), region);- messageId = sesService.sendEmail(sendRequest+ SendEmailRequest inlineRequest = sendRequest.content(new EmailContent.InlineTemplate(subject, text, html, templateData,additionalHeaders))- .build());+ .build();+ sesService.checkTenantSendAccess(inlineRequest, null, regionResolver.getAccountId());+ messageId = sesService.sendEmail(inlineRequest);}} else {throw new AwsException("BadRequestException",@@ -299,10 +299,9 @@ public class SesSendController {? templateName: SesTemplateService.templateNameFromArn(templateArn);gateTemplateName = resolvedName;- EmailTemplate stored = templateService.getTemplate(resolvedName, region);- subject = stored.getSubject();- text = stored.getTextPart();- html = stored.getHtmlPart();+ subject = null;+ text = null;+ html = null;}JsonNode defaultTemplateData = parseTemplateData(template, "TemplateData");@@ -338,8 +337,15 @@ public class SesSendController {// The tenant gate runs only after every part of the request has been parsed and// validated — AWS reports malformed content before a missing tenant (probe-confirmed).- sesService.checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName,- gateTemplateName, regionResolver.getAccountId(), region);+ sesService.checkTenantBulkSendAccess(tenantName, fromEmailAddress, configurationSetName,+ gateTemplateName, entries, regionResolver.getAccountId(), region);+ // SES reports an unknown or DISABLED tenant before an unknown stored template (probe-confirmed).+ if (gateTemplateName != null) {+ EmailTemplate stored = templateService.getTemplate(gateTemplateName, region);+ subject = stored.getSubject();+ text = stored.getTextPart();+ html = stored.getHtmlPart();+ }List<BulkEmailEntryResult> results = sesService.sendBulkEmail(SendBulkEmailRequest.builder().source(fromEmailAddress)diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.javaindex 3c7db34dc0..f4b9fb82ad 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@@ -379,15 +379,19 @@ public class SesService {private String validateEnvelope(SendEmailRequest request) {String source = request.source();- if (!request.hasRecipients()) {- throw new AwsException("InvalidParameterValue", "At least one destination address is required.", 400);- }+ requireRecipients(request);String effectiveConfigSet = resolveDefaultConfigurationSet(request.configurationSetName(), source,request.region());configSetService.validateForSending(effectiveConfigSet, request.region());return effectiveConfigSet;}+ private static void requireRecipients(SendEmailRequest request) {+ if (!request.hasRecipients()) {+ throw new AwsException("InvalidParameterValue", "At least one destination address is required.", 400);+ }+ }+private String sendSimpleEmail(SendEmailRequest request, EmailContent.Simple content, String effectiveConfigSet) {String source = request.source();String region = request.region();@@ -1131,20 +1135,58 @@ public class SesService {/*** The tenant send gate (Phase 4): resolves the tenant with the send-flavored not-found wording,- * then requires every resource the send uses to be associated with it. The tenant's- * SendingStatus is not checked — no API can move it off ENABLED, so the DISABLED gate is not- * emulated. Placement is probe-confirmed: request-shape validation (a missing Content, an empty- * inline template, a missing FromEmailAddress on Simple, the bulk template-content checks) runs- * before the tenant lookup, while the recipient checks, the raw MIME-From derivation, and- * identity verification all lose to the tenant 404.+ * refuses a tenant whose sending is DISABLED, then requires every resource the send uses to be+ * associated with it. Placement is probe-confirmed: request-shape validation (a missing Content,+ * an empty inline template, a missing FromEmailAddress on Simple, the bulk template-content+ * checks) runs before the tenant lookup, while the recipient checks, the raw MIME-From+ * derivation, and identity verification all lose to the tenant 404. The DISABLED refusal also+ * beats identity verification, the association check and a raw message's missing recipients,+ * but an unknown configuration set named by the request is reported before it, and so are the+ * address and recipient checks of a Simple or Template send, which goes through the overload+ * that takes its envelope.*/public void checkTenantSendAccess(String tenantName, String fromEmailAddress,String configurationSetName, String templateName,String accountId, String region) {+ checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName, templateName, accountId,+ region, null, configurationSetName);+ }++ /**+ * The send gate for SendBulkEmail, which refuses a DISABLED tenant before it looks up the+ * configuration set, unlike SendEmail. A request in which no entry names a recipient skips the+ * gate altogether, even for an unknown tenant: each entry is answered on its own instead+ * (probe-confirmed).+ */+ public void checkTenantBulkSendAccess(String tenantName, String fromEmailAddress,+ String configurationSetName, String templateName,+ List<BulkEmailEntry> entries, String accountId, String region) {+ if (!anyBulkRecipient(entries)) {+ return;+ }+ checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName, templateName, accountId,+ region, null, null);+ }++ /**+ * The send gate for a Simple or Template send, whose envelope SES validates before it refuses a+ * DISABLED tenant: a malformed address and a request with no recipient are reported first+ * (probe-confirmed), while a tenant that may send still meets the gate before them.+ */+ public void checkTenantSendAccess(SendEmailRequest envelope, String templateName, String accountId) {+ checkTenantSendAccess(envelope.tenantName(), envelope.source(), envelope.configurationSetName(),+ templateName, accountId, envelope.region(), envelope, envelope.configurationSetName());+ }++ private void checkTenantSendAccess(String tenantName, String fromEmailAddress,+ String configurationSetName, String templateName,+ String accountId, String region, SendEmailRequest envelope,+ String configurationSetBeforeRefusal) {if (tenantName == null) {return;}Tenant tenant = tenantService.tenantForSending(tenantName, region, accountId);+ requireSendingEnabled(tenant, configurationSetBeforeRefusal, region, envelope);String arnPrefix = "arn:" + AwsRegions.partitionFor(region) + ":ses:" + region + ":" + accountId + ":";List<SesTenantService.AssociationResource> used = new ArrayList<>();if (fromEmailAddress != null && !fromEmailAddress.isBlank()) {@@ -1175,7 +1217,8 @@ public class SesService {* the effective sender comes from the MIME {@code From} header, the same derivation* {@code sendRawEmail} applies, so the gate must resolve it the same way before checking.* {@code hasDestination} says whether the request named any recipient; when it did not and the- * MIME To, Cc and Bcc headers are empty too, only the tenant's existence is checked.+ * MIME To, Cc and Bcc headers are empty too, only the tenant's existence and sending status+ * are checked.*/public void checkTenantRawSendAccess(String tenantName, String fromEmailAddress,String rawMessage, boolean hasDestination,@@ -1184,10 +1227,12 @@ public class SesService {return;}SmtpRelay.RawMessageHeaders headers = SmtpRelay.parseRawHeaders(rawMessage);- // AWS checks that the tenant exists, then reports a message with no recipients anywhere- // ahead of the association gate (probe-confirmed), so that error is left to sendRawEmail.+ // AWS checks that the tenant exists and may send, then reports a message with no recipients+ // anywhere ahead of the association gate (probe-confirmed), so that error is left to+ // sendRawEmail.if (!hasDestination && SendEmailRequest.recipients(headers.to(), headers.cc(), headers.bcc()).isEmpty()) {- tenantService.tenantForSending(tenantName, region, accountId);+ requireSendingEnabled(tenantService.tenantForSending(tenantName, region, accountId),+ firstNonBlank(configurationSetName, headers.configurationSet()), region, null);return;}String effectiveSource = fromEmailAddress;@@ -1201,6 +1246,22 @@ public class SesService {accountId, region);}+ private void requireSendingEnabled(Tenant tenant, String configurationSetName, String region,+ SendEmailRequest envelope) {+ if (!"DISABLED".equals(tenant.sendingStatus())) {+ return;+ }+ if (envelope != null) {+ SesAddressSyntax.requireEnvelope(envelope);+ requireRecipients(envelope);+ }+ if (configurationSetName != null && !configurationSetName.isBlank()) {+ configSetService.get(configurationSetName, region);+ }+ throw new AwsException("MessageRejected", "Sending disabled for <" + tenant.tenantArn()+ + ">. For more information, please check the resource configuration and status.", 400);+ }+// The gate names the identity the way AWS did in the probed error: the exact address identity// when one exists, otherwise the domain identity the address falls under. The sender may carry// display-name syntax ("Name <a@b>"), so the bare address is extracted first.@@ -1682,11 +1743,18 @@ public class SesService {}}- boolean requestHasRecipient = request.entries().stream().anyMatch(SesService::hasNonNullRecipient);+ // When no entry names a recipient, SES answers every entry the same, whatever its lists hold+ // (probe-confirmed for null elements, empty lists and an empty Destination).+ if (!anyBulkRecipient(request.entries())) {+ return request.entries().stream()+ .map(entry -> BulkEmailEntryResult.failure(BulkEmailEntryResult.Status.INVALID_PARAMETER,+ "Destination cannot be empty"))+ .toList();+ }List<BulkEmailEntryResult> results = new ArrayList<>(request.entries().size());for (BulkEmailEntry entry : request.entries()) {try {- SesAddressSyntax.requireBulkDestination(entry, request.replyToAddresses(), requestHasRecipient);+ SesAddressSyntax.requireBulkDestination(entry, request.replyToAddresses());JsonNode merged = mergeTemplateData(template.templateData(), entry.replacementTemplateData());List<MessageTag> mergedTags = mergeEmailTags(request.defaultEmailTags(), entry.replacementEmailTags());List<MessageHeader> mergedHeaders = mergeHeaders(template.headers(), entry.replacementHeaders());@@ -1723,8 +1791,9 @@ public class SesService {return results;}- private static boolean hasNonNullRecipient(BulkEmailEntry entry) {- return Stream.of(entry.toAddresses(), entry.ccAddresses(), entry.bccAddresses())+ private static boolean anyBulkRecipient(List<BulkEmailEntry> entries) {+ return entries.stream()+ .flatMap(entry -> Stream.of(entry.toAddresses(), entry.ccAddresses(), entry.bccAddresses())).filter(Objects::nonNull).flatMap(List::stream).anyMatch(Objects::nonNull);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.javaindex 628011d46d..43ed772d5d 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@@ -114,7 +114,7 @@ public class SesTenantService implements SesTaggable {String tenantId = generateTenantId();String tenantArn = AwsArnUtils.Arn.of("ses", region, accountId, "tenant/" + tenantName + "/" + tenantId).toString();Tenant tenant = new Tenant(tenantName, tenantId, tenantArn, Instant.now(clock), tags,- "ENABLED", attrs);+ "ENABLED", attrs, null, null);// Only the check-then-put needs to be atomic, so two concurrent creates for the same name can't// both observe the key as absent; the id/ARN/record are built outside the lock.synchronized (tenantMutationLock) {@@ -241,6 +241,33 @@ public class SesTenantService implements SesTaggable {.findFirst();}+ /**+ * Resolves a tenant by its full ARN, for the reputation entity operations: unlike the tag+ * operations, SES matches the whole ARN there, name and id both (probe-confirmed).+ */+ public Optional<Tenant> findByArn(String tenantArn, String region) {+ String resource = AwsArnUtils.resourceIfArnFor(tenantArn, "ses").orElse("");+ String[] segments = resource.split("/", -1);+ if (segments.length != 3 || !"tenant".equals(segments[0])) {+ return Optional.empty();+ }+ return tenantStore.get(tenantKey(region, segments[1]))+ .filter(t -> t.tenantArn().equals(tenantArn));+ }++ /**+ * Applies {@code mutation} to the tenant with this ARN under the shared lock, so a concurrent+ * tag, suppression-attribute or reputation update is not overwritten by a stale copy. Returns+ * the updated tenant, empty when no tenant has the ARN.+ */+ public Optional<Tenant> updateByArn(String tenantArn, String region, UnaryOperator<Tenant> mutation) {+ synchronized (tenantMutationLock) {+ Optional<Tenant> updated = findByArn(tenantArn, region).map(mutation);+ updated.ifPresent(t -> tenantStore.put(tenantKey(region, t.tenantName()), t));+ return updated;+ }+ }+/*** The name/id decomposition of a tenant tag ARN's resource remainder ({@code <name>/<tenantId>}* after the generic dispatch split off the {@code tenant/} type segment). AWS parses a remainderdiff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesV2Json.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesV2Json.javaindex 3a19a2ebbc..88fd28817a 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesV2Json.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesV2Json.java@@ -15,6 +15,7 @@ import java.util.LinkedHashMap;import java.util.List;import java.util.Locale;import java.util.Map;+import java.util.function.Predicate;/*** Helpers shared by the SES v2 REST JSON controllers: body and member shape checks that answer@@ -207,6 +208,22 @@ final class SesV2Json {* an empty one.*/static Map<String, String> filterValues(Map<String, String> filter, List<String> keys) {+ return filterValues(filter, keys, String::isEmpty, "Member must have length greater than or equal to 1");+ }++ /**+ * As above, for a filter whose values are bounded above too. SES printed both bounds for an+ * empty value, so a value over the bound is taken to be answered the same way.+ */+ static Map<String, String> filterValues(Map<String, String> filter, List<String> keys, int maxValueLength) {+ return filterValues(filter, keys,+ v -> v.isEmpty() || v.codePointCount(0, v.length()) > maxValueLength,+ "Member must have length less than or equal to " + maxValueLength+ + ", Member must have length greater than or equal to 1");+ }++ private static Map<String, String> filterValues(Map<String, String> filter, List<String> keys,+ Predicate<String> invalidValue, String valueConstraint) {if (filter == null) {return Map.of();}@@ -215,10 +232,10 @@ final class SesV2Json {+ "failed to satisfy constraint: Map keys must satisfy constraint: "+ "[Member must satisfy enum value set: [" + String.join(", ", keys) + "]]");}- if (filter.containsValue("")) {+ if (filter.values().stream().anyMatch(v -> v != null && invalidValue.test(v))) {throw SmithyValidationErrors.badRequest( "Value at 'filter' "+ "failed to satisfy constraint: Map value must satisfy constraint: "- + "[Member must have length greater than or equal to 1]");+ + "[" + valueConstraint + "]");}Map<String, String> values = new LinkedHashMap<>();filter.forEach((key, value) -> {diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesV2RequestShapes.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesV2RequestShapes.javaindex 511851b2e9..87e6664519 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesV2RequestShapes.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesV2RequestShapes.java@@ -17,7 +17,9 @@ import java.util.Set;** <p>An operation calls this when its body nests a structure in a structure or holds a list of* structures, where member-by-member checks drift apart. A flat body, a {@code Tags}-only body and- * a list operation's map {@code Filter} keep the {@link SesV2Json} member helpers.+ * a list operation's map {@code Filter} keep the {@link SesV2Json} member helpers, except in the+ * reputation entity operations, which were added after this check and call it although their+ * bodies are flat.** <p>AWS reads the body in order and reports the first bad member, without naming it. A map* container answers like a structure, except that a scalar for it is "Expected map or null". Onlydiff --git a/src/main/java/io/github/hectorvent/floci/services/ses/address/SesAddressSyntax.java b/src/main/java/io/github/hectorvent/floci/services/ses/address/SesAddressSyntax.javaindex a22384d381..da9e116470 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/address/SesAddressSyntax.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/address/SesAddressSyntax.java@@ -32,7 +32,6 @@ public final class SesAddressSyntax {private static final List<String> RAW_CHECKED_HEADERS = List.of("To", "Cc", "Bcc");private static final String MISSING_FINAL_DOMAIN = "Missing final '@domain'";private static final String NULL_ADDRESS = "Invalid email address null.";- private static final String EMPTY_DESTINATION = "Destination cannot be empty";private static final String PHRASE_SPECIALS = "()<>@,;:\\\".[]";private static final String ADDRESS_SPECIALS = "()<>,;:\\\"[]";@@ -198,26 +197,24 @@ public final class SesAddressSyntax {* every entry, not as a request error (probe-confirmed). An address list of the wrong JSON type* never reaches this check: the controller rejects the whole request with SerializationException.*- * <p>A null element passes deserialization and fails here as "Invalid email address null.",- * unless no entry of the request has a non-null recipient: then an entry holding one answers- * "Destination cannot be empty" (probe-confirmed for To lists of nulls; how SES words an entry- * whose lists are merely empty was not probed, so that case is left as it was).+ * <p>A null element passes deserialization and fails here as "Invalid email address null.".+ * A request in which no entry has a non-null recipient never reaches this check: the caller+ * answers every entry "Destination cannot be empty" instead.*/- public static void requireBulkDestination(BulkEmailEntry entry, List<String> replyToAddresses,- boolean requestHasRecipient) {+ public static void requireBulkDestination(BulkEmailEntry entry, List<String> replyToAddresses) {for (List<String> addresses : Arrays.asList(entry.toAddresses(), entry.ccAddresses(), entry.bccAddresses())) {- requireBulkAddresses(addresses, requestHasRecipient ? NULL_ADDRESS : EMPTY_DESTINATION);+ requireBulkAddresses(addresses);}- requireBulkAddresses(replyToAddresses, NULL_ADDRESS);+ requireBulkAddresses(replyToAddresses);}- private static void requireBulkAddresses(List<String> addresses, String nullMessage) {+ private static void requireBulkAddresses(List<String> addresses) {if (addresses == null) {return;}for (String address : addresses) {if (address == null) {- throw new AwsException("InvalidParameterValue", nullMessage, 400);+ throw new AwsException("InvalidParameterValue", NULL_ADDRESS, 400);}require(address);}diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/ReputationStatusRecord.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/ReputationStatusRecord.javanew file mode 100644index 0000000000..97ab0065a2--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/ReputationStatusRecord.java@@ -0,0 +1,13 @@+package io.github.hectorvent.floci.services.ses.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;++/**+ * The SES v2 {@code StatusRecord} of a reputation entity: a {@code SendingStatus} (ENABLED /+ * REINSTATED / DISABLED), its cause and when it last changed.+ */+@RegisterForReflection+public record ReputationStatusRecord(String status, String cause, Instant lastUpdatedTimestamp) {+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/Tenant.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/Tenant.javaindex 3927f4841e..903861b417 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/model/Tenant.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/Tenant.java@@ -8,7 +8,11 @@ import java.util.List;/*** A SES v2 tenant (multi-tenancy). Created by {@code CreateTenant} and returned by* {@code GetTenant}/{@code ListTenants}. {@code sendingStatus} is the AWS {@code SendingStatus} enum- * (ENABLED / REINSTATED / DISABLED); a freshly created tenant is ENABLED.+ * (ENABLED / REINSTATED / DISABLED): the tenant's aggregate status as a reputation entity, ENABLED+ * for a freshly created tenant. {@code reputationPolicy} is the policy ARN set by+ * {@code UpdateReputationEntityPolicy}, null for the default Standard policy, and+ * {@code customerManagedStatus} the record set by {@code UpdateReputationEntityCustomerManagedStatus},+ * null until the first update.*/@RegisterForReflectionpublic record Tenant(String tenantName,@@ -17,16 +21,34 @@ public record Tenant(String tenantName,Instant createdTimestamp,List<Tag> tags,String sendingStatus,- TenantSuppressionAttributes suppressionAttributes) {+ TenantSuppressionAttributes suppressionAttributes,+ String reputationPolicy,+ ReputationStatusRecord customerManagedStatus) {/** Copy with different tags (records are immutable; the store is replace-only). */public Tenant withTags(List<Tag> newTags) {return new Tenant(tenantName, tenantId, tenantArn, createdTimestamp, newTags, sendingStatus,- suppressionAttributes);+ suppressionAttributes, reputationPolicy, customerManagedStatus);}/** Copy with different suppression attributes (records are immutable; the store is replace-only). */public Tenant withSuppressionAttributes(TenantSuppressionAttributes attrs) {- return new Tenant(tenantName, tenantId, tenantArn, createdTimestamp, tags, sendingStatus, attrs);+ return new Tenant(tenantName, tenantId, tenantArn, createdTimestamp, tags, sendingStatus, attrs,+ reputationPolicy, customerManagedStatus);+ }++ /** Copy with a different reputation management policy ARN. */+ public Tenant withReputationPolicy(String policy) {+ return new Tenant(tenantName, tenantId, tenantArn, createdTimestamp, tags, sendingStatus,+ suppressionAttributes, policy, customerManagedStatus);+ }++ /**+ * Copy with a different customer-managed status. SES manages no status of its own here, so the+ * customer-managed one is the aggregate the tenant reports as its {@code sendingStatus}.+ */+ public Tenant withCustomerManagedStatus(ReputationStatusRecord status) {+ return new Tenant(tenantName, tenantId, tenantArn, createdTimestamp, tags, status.status(),+ suppressionAttributes, reputationPolicy, status);}}diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesReputationEntityMemberTypeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesReputationEntityMemberTypeIntegrationTest.javanew file mode 100644index 0000000000..01a00324fd--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesReputationEntityMemberTypeIntegrationTest.java@@ -0,0 +1,67 @@+package io.github.hectorvent.floci.services.ses;++import io.quarkus.test.junit.QuarkusTest;+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.github.hectorvent.floci.services.ses.SesV2SerializationErrors.EXPECTED_MAP;+import static io.github.hectorvent.floci.services.ses.SesV2SerializationErrors.LIST;+import static io.github.hectorvent.floci.services.ses.SesV2SerializationErrors.NUMBER;+import static io.github.hectorvent.floci.services.ses.SesV2SerializationErrors.STRUCTURE;+import static io.github.hectorvent.floci.services.ses.SesV2SerializationErrors.assertSerializationException;++/**+ * The reputation entity operations check their body against the SES v2 shapes, so a member of the+ * wrong JSON type is a SerializationException ahead of every other check. The updates name an+ * entity type and a reference that would both be refused, to show the body is read first.+ */+@QuarkusTest+class SesReputationEntityMemberTypeIntegrationTest {++ private static final String LIST_PATH = "/v2/email/reputation/entities";+ private static final String ENTITY_PATH = "/v2/email/reputation/entities/FOO/hello";++ static Stream<Arguments> listReputationEntitiesCases() {+ return Stream.of(+ Arguments.of("stringFilter", "{\"Filter\": \"x\"}", EXPECTED_MAP),+ Arguments.of("arrayFilter", "{\"Filter\": []}", LIST),+ Arguments.of("numericFilterValue", "{\"Filter\": {\"SENDING_STATUS\": 1}}", NUMBER),+ Arguments.of("objectNextToken", "{\"NextToken\": {}}", STRUCTURE),+ Arguments.of("arrayNextToken", "{\"NextToken\": []}", LIST));+ }++ static Stream<Arguments> updateReputationEntityPolicyCases() {+ return Stream.of(+ Arguments.of("numericPolicy", "{\"ReputationEntityPolicy\": 1}", NUMBER),+ Arguments.of("objectPolicy", "{\"ReputationEntityPolicy\": {}}", STRUCTURE),+ Arguments.of("arrayPolicy", "{\"ReputationEntityPolicy\": []}", LIST));+ }++ static Stream<Arguments> updateReputationEntityCustomerManagedStatusCases() {+ return Stream.of(+ Arguments.of("booleanStatus", "{\"SendingStatus\": true}", "TRUE_VALUE can not be converted to a String"),+ Arguments.of("objectStatus", "{\"SendingStatus\": {}}", STRUCTURE),+ Arguments.of("arrayStatus", "{\"SendingStatus\": []}", LIST));+ }++ @ParameterizedTest(name = "{0}")+ @MethodSource("listReputationEntitiesCases")+ void listReputationEntities_wrongMemberType(String caseName, String body, String message) {+ assertSerializationException("POST", LIST_PATH, body, message);+ }++ @ParameterizedTest(name = "{0}")+ @MethodSource("updateReputationEntityPolicyCases")+ void updateReputationEntityPolicy_wrongMemberType(String caseName, String body, String message) {+ assertSerializationException("PUT", ENTITY_PATH + "/policy", body, message);+ }++ @ParameterizedTest(name = "{0}")+ @MethodSource("updateReputationEntityCustomerManagedStatusCases")+ void updateReputationEntityCustomerManagedStatus_wrongMemberType(String caseName, String body, String message) {+ assertSerializationException("PUT", ENTITY_PATH + "/customer-managed-status", body, message);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesReputationEntityServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesReputationEntityServiceTest.javanew file mode 100644index 0000000000..d8e72d0398--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesReputationEntityServiceTest.java@@ -0,0 +1,123 @@+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.SesReputationEntityService.ReputationEntity;+import io.github.hectorvent.floci.services.ses.model.Tenant;+import io.github.hectorvent.floci.testing.MutableClock;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.security.SecureRandom;+import java.time.Duration;+import java.time.Instant;+import java.util.List;+import java.util.Locale;+import java.util.Map;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++class SesReputationEntityServiceTest {++ private static final String REGION = "us-east-1";+ private static final String ACCOUNT = "000000000000";++ private MutableClock clock;+ private SesTenantService tenants;+ private SesReputationEntityService service;++ @BeforeEach+ void setUp() {+ clock = new MutableClock();+ tenants = new SesTenantService(new InMemoryStorage<>(), new InMemoryStorage<>(), clock, new SecureRandom());+ service = new SesReputationEntityService(tenants, clock);+ }++ @Test+ void get_defaultPolicyFollowsTheRegionsPartition() {+ Tenant cn = tenants.createTenant("acme", List.of(), ACCOUNT, "cn-north-1");++ ReputationEntity entity = service.get("RESOURCE", cn.tenantArn(), "cn-north-1");++ assertEquals("arn:aws-cn:ses:cn-north-1:aws:reputation-policy/standard", entity.policy());+ assertNull(entity.customerManagedStatus());+ assertEquals("ENABLED", entity.sendingStatusAggregate());+ }++ @Test+ void get_isRegionScoped() {+ Tenant tenant = tenants.createTenant("acme", List.of(), ACCOUNT, REGION);++ AwsException e = assertThrows(AwsException.class,+ () -> service.get("RESOURCE", tenant.tenantArn(), "us-west-2"));++ assertEquals("BadRequestException", e.getErrorCode());+ assertEquals(400, e.getHttpStatus());+ }++ @Test+ void updatePolicy_checksOnlyTheAccountAndTheResource() {+ Tenant tenant = tenants.createTenant("acme", List.of(), ACCOUNT, REGION);++ for (String policy : List.of("arn:aws-cn:ses:cn-north-1:aws:reputation-policy/none",+ "arn:aws-nope:ses:mars-1:aws:reputation-policy/strict",+ "arn:aws:ses::aws:reputation-policy/standard")) {+ service.updatePolicy("RESOURCE", tenant.tenantArn(), policy, REGION);+ assertEquals(policy, service.get("RESOURCE", tenant.tenantArn(), REGION).policy());+ }+ for (String policy : List.of("arn:aws:sqs:us-east-1:aws:reputation-policy/none",+ "arn:aws:ses:us-east-1:aws:reputation-policy/",+ "arn:aws:ses:us-east-1:aws:reputation-policy/strict/x",+ "arn:aws:ses:us-east-1:aws:policy/none")) {+ AwsException e = assertThrows(AwsException.class,+ () -> service.updatePolicy("RESOURCE", tenant.tenantArn(), policy, REGION));+ assertEquals("Provided resource identifier is invalid", e.getMessage());+ }+ }++ @Test+ void updateStatus_stampsEveryCallAndKeepsTheOtherTenantState() {+ Tenant tenant = tenants.createTenant("acme", List.of(), ACCOUNT, REGION);+ service.updatePolicy("RESOURCE", tenant.tenantArn(), "arn:aws:ses:us-east-1:aws:reputation-policy/strict",+ REGION);++ service.updateCustomerManagedStatus("RESOURCE", tenant.tenantArn(), "DISABLED", REGION);+ Instant first = service.get("RESOURCE", tenant.tenantArn(), REGION).customerManagedStatus()+ .lastUpdatedTimestamp();+ clock.advance(Duration.ofMinutes(5));+ service.updateCustomerManagedStatus("RESOURCE", tenant.tenantArn(), "DISABLED", REGION);++ ReputationEntity entity = service.get("RESOURCE", tenant.tenantArn(), REGION);+ assertTrue(entity.customerManagedStatus().lastUpdatedTimestamp().isAfter(first.plus(Duration.ofMinutes(5))));+ assertEquals("DISABLED", entity.sendingStatusAggregate());+ assertEquals("arn:aws:ses:us-east-1:aws:reputation-policy/strict", entity.policy());+ assertEquals("DISABLED", tenants.getTenant("acme", REGION).sendingStatus());+ }++ @Test+ void list_byReference_prefixIsCaseSensitive() {+ Tenant b = tenants.createTenant("beta", List.of(), ACCOUNT, REGION);+ Tenant a = tenants.createTenant("alpha", List.of(), ACCOUNT, REGION);++ assertEquals(List.of(a.tenantArn(), b.tenantArn()),+ service.list(Map.of(), null, null, REGION).items().stream().map(ReputationEntity::reference).toList());+ assertTrue(service.list(Map.of("ENTITY_REFERENCE_PREFIX", a.tenantArn().toUpperCase(Locale.ROOT)),+ null, null, REGION).items().isEmpty());+ }++ @Test+ void list_tokenFromAnotherRegion_isUnreadableNotBoundElsewhere() {+ tenants.createTenant("alpha", List.of(), ACCOUNT, "us-west-2");+ tenants.createTenant("beta", List.of(), ACCOUNT, "us-west-2");+ PaginatedResult<ReputationEntity> page = service.list(Map.of(), 1, null, "us-west-2");++ AwsException e = assertThrows(AwsException.class,+ () -> service.list(Map.of(), 1, page.nextToken(), REGION));++ assertEquals("Failed to deserialize token. ", e.getMessage());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesReputationEntityV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesReputationEntityV2IntegrationTest.javanew file mode 100644index 0000000000..85e22aa191--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesReputationEntityV2IntegrationTest.java@@ -0,0 +1,298 @@+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.net.URLEncoder;+import java.nio.charset.StandardCharsets;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.contains;+import static org.hamcrest.Matchers.empty;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasItem;+import static org.hamcrest.Matchers.hasKey;+import static org.hamcrest.Matchers.not;+import static org.hamcrest.Matchers.notNullValue;+import static org.hamcrest.Matchers.nullValue;++/**+ * Integration tests for the SES v2 reputation entity operations. Every tenant is an entity+ * referenced by its full ARN; shapes, messages and precedence follow the 2026-10-23 probes.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class SesReputationEntityV2IntegrationTest {++ private static final String AUTH =+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request";+ private static final String PREFIX = "arn:aws:ses:us-east-1:000000000000:tenant/floci-rep-it-";+ private static final String POLICY_PREFIX = "arn:aws:ses:us-east-1:aws:reputation-policy/";+ private static final String INVALID_IDENTIFIER = "Provided resource identifier is invalid";++ private static String arnA;+ private static String arnB;++ // The reference is sent percent-encoded as the SDKs send it, so RestAssured must not encode it again.+ private static RequestSpecification v2() {+ return given().urlEncodingEnabled(false).contentType("application/json").header("Authorization", AUTH);+ }++ private static String entityPath(String type, String reference) {+ return "/v2/email/reputation/entities/" + type + "/" + URLEncoder.encode(reference, StandardCharsets.UTF_8);+ }++ private static String createTenant(String name) {+ return v2().body("{\"TenantName\":\"" + name + "\"}")+ .when().post("/v2/email/tenants").then().statusCode(200)+ .extract().path("TenantArn");+ }++ private static String prefixFilter(String extra) {+ return "{\"Filter\":{\"ENTITY_REFERENCE_PREFIX\":\"" + PREFIX + "\"}" + extra + "}";+ }++ @Test+ @Order(1)+ void setup_tenants() {+ arnA = createTenant("floci-rep-it-a");+ arnB = createTenant("floci-rep-it-b");+ }++ @Test+ @Order(2)+ void list_everyTenantIsAnEntityWithEveryMemberRendered() {+ v2().body(prefixFilter(""))+ .when().post("/v2/email/reputation/entities").then().statusCode(200)+ .body("$", hasKey("NextToken"))+ .body("NextToken", nullValue())+ .body("ReputationEntities.ReputationEntityReference", contains(arnA, arnB))+ .body("ReputationEntities[0]", hasKey("AwsSesManagedStatus"))+ .body("ReputationEntities[0].AwsSesManagedStatus", nullValue())+ .body("ReputationEntities[0]", hasKey("CustomerManagedStatus"))+ .body("ReputationEntities[0].CustomerManagedStatus", nullValue())+ .body("ReputationEntities[0].ReputationEntityType", equalTo("RESOURCE"))+ .body("ReputationEntities[0].ReputationImpact", equalTo("NONE"))+ .body("ReputationEntities[0].ReputationManagementPolicy", equalTo(POLICY_PREFIX + "standard"))+ .body("ReputationEntities[0].SendingStatusAggregate", equalTo("ENABLED"));+ }++ @Test+ @Order(3)+ void get_matchesOnlyTheFullArn() {+ v2().when().get(entityPath("RESOURCE", arnA)).then().statusCode(200)+ .body("ReputationEntity.ReputationEntityReference", equalTo(arnA))+ .body("ReputationEntity.SendingStatusAggregate", equalTo("ENABLED"));++ String tenantId = arnA.substring(arnA.lastIndexOf('/') + 1);+ for (String other : new String[] {+ "arn:aws:ses:us-east-1:000000000000:tenant/" + tenantId,+ PREFIX + "a",+ PREFIX + "wrong/" + tenantId,+ arnA.replace("us-east-1", "us-west-2"),+ "arn:aws:ses:us-east-1:000000000000:identity/example.com"}) {+ v2().when().get(entityPath("RESOURCE", other)).then().statusCode(400)+ .body("__type", equalTo("BadRequestException"))+ .body("message", equalTo("ReputationEntity <" + other + "> does not exist"));+ }+ }++ @Test+ @Order(4)+ void literalSlashesInTheReference_reachNoRoute() {+ v2().when().get("/v2/email/reputation/entities/RESOURCE/" + arnA).then().statusCode(404);+ v2().body("{\"SendingStatus\":\"DISABLED\"}")+ .when().put("/v2/email/reputation/entities/RESOURCE/" + arnA + "/customer-managed-status")+ .then().statusCode(404);+ v2().body("{\"TenantName\":\"floci-rep-it-a\"}")+ .when().post("/v2/email/tenants/get").then().statusCode(200)+ .body("Tenant.SendingStatus", equalTo("ENABLED"));+ }++ @Test+ @Order(5)+ void get_typeThenReferenceFormat() {+ v2().when().get(entityPath("FOO", "hello")).then().statusCode(400)+ .body("__type", equalTo("BadRequestException"))+ .body("message", equalTo("1 validation error detected: Value at 'reputationEntityType' failed "+ + "to satisfy constraint: Member must satisfy enum value set: [RESOURCE]"));+ v2().when().get(entityPath("RESOURCE", "hello")).then().statusCode(400)+ .body("message", equalTo(INVALID_IDENTIFIER));+ v2().when().get(entityPath("RESOURCE", "arn:aws:sqs:us-east-1:000000000000:q")).then().statusCode(400)+ .body("message", equalTo(INVALID_IDENTIFIER));+ }++ @Test+ @Order(6)+ void updatePolicy_storesTheGivenArn() {+ v2().body("{\"ReputationEntityPolicy\":\"" + POLICY_PREFIX + "strict\"}")+ .when().put(entityPath("RESOURCE", arnA) + "/policy").then().statusCode(200);+ v2().when().get(entityPath("RESOURCE", arnA)).then().statusCode(200)+ .body("ReputationEntity.ReputationManagementPolicy", equalTo(POLICY_PREFIX + "strict"));++ String otherRegion = "arn:aws:ses:us-west-2:aws:reputation-policy/none";+ v2().body("{\"ReputationEntityPolicy\":\"" + otherRegion + "\"}")+ .when().put(entityPath("RESOURCE", arnA) + "/policy").then().statusCode(200);+ v2().when().get(entityPath("RESOURCE", arnA)).then().statusCode(200)+ .body("ReputationEntity.ReputationManagementPolicy", equalTo(otherRegion));+ }++ @Test+ @Order(7)+ void updatePolicy_checksThePolicyFirst() {+ for (String body : new String[] {+ "{}",+ "{\"ReputationEntityPolicy\":\"standard\"}",+ "{\"ReputationEntityPolicy\":\"" + POLICY_PREFIX + "lax\"}",+ "{\"ReputationEntityPolicy\":\"" + POLICY_PREFIX + "STANDARD\"}",+ "{\"ReputationEntityPolicy\":\"arn:aws:ses:us-east-1:000000000000:reputation-policy/standard\"}"}) {+ v2().body(body).when().put(entityPath("RESOURCE", arnA) + "/policy").then().statusCode(400)+ .body("__type", equalTo("BadRequestException"))+ .body("message", equalTo(INVALID_IDENTIFIER));+ }+ // Even a bad entity type loses to a bad policy.+ v2().body("{\"ReputationEntityPolicy\":\"x\"}")+ .when().put(entityPath("FOO", PREFIX + "ghost/tn-0") + "/policy").then().statusCode(400)+ .body("message", equalTo(INVALID_IDENTIFIER));+ v2().body("{\"ReputationEntityPolicy\":\"" + POLICY_PREFIX + "standard\"}")+ .when().put(entityPath("RESOURCE", PREFIX + "ghost/tn-0") + "/policy").then().statusCode(400)+ .body("message", equalTo("ReputationEntity <" + PREFIX + "ghost/tn-0> does not exist"));+ }++ @Test+ @Order(8)+ void updateStatus_disabledIsTheAggregateEverywhere() {+ v2().body("{\"SendingStatus\":\"DISABLED\"}")+ .when().put(entityPath("RESOURCE", arnA) + "/customer-managed-status").then().statusCode(200);++ v2().when().get(entityPath("RESOURCE", arnA)).then().statusCode(200)+ .body("ReputationEntity.CustomerManagedStatus.Status", equalTo("DISABLED"))+ .body("ReputationEntity.CustomerManagedStatus.Cause", equalTo("Status manually updated."))+ .body("ReputationEntity.CustomerManagedStatus.LastUpdatedTimestamp", notNullValue())+ .body("ReputationEntity.AwsSesManagedStatus", nullValue())+ .body("ReputationEntity.SendingStatusAggregate", equalTo("DISABLED"));+ v2().body("{\"TenantName\":\"floci-rep-it-a\"}")+ .when().post("/v2/email/tenants/get").then().statusCode(200)+ .body("Tenant.SendingStatus", equalTo("DISABLED"));+ v2().body("{\"Filter\":{\"SENDING_STATUS\":\"DISABLED\",\"TENANT_NAME_CONTAINS\":\"floci-rep-it-\"}}")+ .when().post("/v2/email/tenants/list").then().statusCode(200)+ .body("Tenants.TenantArn", contains(arnA));+ // The entity filter takes one key, so other classes' tenants may show up here as well.+ v2().body("{\"Filter\":{\"SENDING_STATUS\":\"DISABLED\"}}")+ .when().post("/v2/email/reputation/entities").then().statusCode(200)+ .body("ReputationEntities.ReputationEntityReference", hasItem(arnA))+ .body("ReputationEntities.ReputationEntityReference", not(hasItem(arnB)));++ // The same status again is accepted, not a conflict.+ v2().body("{\"SendingStatus\":\"DISABLED\"}")+ .when().put(entityPath("RESOURCE", arnA) + "/customer-managed-status").then().statusCode(200);+ }++ @Test+ @Order(9)+ void updateStatus_referenceThenStatusThenExistence() {+ v2().body("{}")+ .when().put(entityPath("RESOURCE", "hello") + "/customer-managed-status").then().statusCode(400)+ .body("message", equalTo(INVALID_IDENTIFIER));+ v2().body("{}")+ .when().put(entityPath("RESOURCE", arnA) + "/customer-managed-status").then().statusCode(400)+ .body("message", equalTo("1 validation error detected: Value at 'sendingStatus' failed to "+ + "satisfy constraint: Member must not be null"));+ v2().body("{\"SendingStatus\":\"PAUSED\"}")+ .when().put(entityPath("RESOURCE", PREFIX + "ghost/tn-0") + "/customer-managed-status")+ .then().statusCode(400)+ .body("message", equalTo("1 validation error detected: Value at 'sendingStatus' failed to "+ + "satisfy constraint: Member must satisfy enum value set: [ENABLED, REINSTATED, DISABLED]"));+ v2().body("{\"SendingStatus\":\"ENABLED\"}")+ .when().put(entityPath("RESOURCE", PREFIX + "ghost/tn-0") + "/customer-managed-status")+ .then().statusCode(400)+ .body("__type", equalTo("BadRequestException"))+ .body("message", equalTo("ReputationEntity <" + PREFIX + "ghost/tn-0> does not exist"));+ }++ @Test+ @Order(10)+ void list_filterValues() {+ v2().body("{\"Filter\":{\"SENDING_STATUS\":\"ENABLED\",\"ENTITY_TYPE\":\"RESOURCE\"}}")+ .when().post("/v2/email/reputation/entities").then().statusCode(400)+ .body("message", equalTo("Too many filters provided."));+ for (String[] bad : new String[][] {+ {"SENDING_STATUS", "disabled"}, {"ENTITY_TYPE", "resource"}, {"REPUTATION_IMPACT", "none"}}) {+ v2().body("{\"Filter\":{\"" + bad[0] + "\":\"" + bad[1] + "\"}}")+ .when().post("/v2/email/reputation/entities").then().statusCode(400)+ .body("__type", equalTo("BadRequestException"))+ .body("message", equalTo("Invalid reputation entity " + bad[0] + " specified"));+ }+ v2().body("{\"Filter\":{\"REPUTATION_IMPACT\":\"MEDIUM\"}}")+ .when().post("/v2/email/reputation/entities").then().statusCode(200)+ .body("ReputationEntities", empty());+ v2().body("{\"Filter\":{\"FOO\":\"x\"}}")+ .when().post("/v2/email/reputation/entities").then().statusCode(400)+ .body("message", equalTo("1 validation error detected: Value at 'filter' failed to satisfy "+ + "constraint: Map keys must satisfy constraint: [Member must satisfy enum value set: "+ + "[ENTITY_REFERENCE_PREFIX, REPUTATION_IMPACT, ENTITY_TYPE, SENDING_STATUS]]"));+ v2().body("{\"Filter\":{\"SENDING_STATUS\":\"\"}}")+ .when().post("/v2/email/reputation/entities").then().statusCode(400)+ .body("message", equalTo("1 validation error detected: Value at 'filter' failed to satisfy "+ + "constraint: Map value must satisfy constraint: [Member must have length less than "+ + "or equal to 512, Member must have length greater than or equal to 1]"));+ v2().body("{\"Filter\":{\"ENTITY_REFERENCE_PREFIX\":\"" + PREFIX.replace("floci-rep-it-", "FLOCI-REP-IT-") + "\"}}")+ .when().post("/v2/email/reputation/entities").then().statusCode(200)+ .body("ReputationEntities", empty());+ }++ @Test+ @Order(11)+ void list_paging() {+ String token = v2().body(prefixFilter(",\"PageSize\":1"))+ .when().post("/v2/email/reputation/entities").then().statusCode(200)+ .body("ReputationEntities.ReputationEntityReference", contains(arnA))+ .extract().path("NextToken");+ v2().body(prefixFilter(",\"PageSize\":1,\"NextToken\":\"" + token + "\""))+ .when().post("/v2/email/reputation/entities").then().statusCode(200)+ .body("ReputationEntities.ReputationEntityReference", contains(arnB))+ .body("NextToken", nullValue());+ v2().body("{\"PageSize\":1,\"NextToken\":\"" + token + "\"}")+ .when().post("/v2/email/reputation/entities").then().statusCode(400)+ .body("message", equalTo("Pagination token is bound to a different set of filtering parameters"));+ for (String bad : new String[] {"garbage", ""}) {+ v2().body("{\"NextToken\":\"" + bad + "\"}")+ .when().post("/v2/email/reputation/entities").then().statusCode(400)+ .body("message", equalTo("Failed to deserialize token. "));+ }+ // The page size is checked before the filter and the token.+ v2().body("{\"PageSize\":0,\"NextToken\":\"garbage\",\"Filter\":{\"SENDING_STATUS\":\"X\"}}")+ .when().post("/v2/email/reputation/entities").then().statusCode(400)+ .body("message", equalTo("The page size must be between 1 and 1000"));+ v2().body("{\"PageSize\":1001}")+ .when().post("/v2/email/reputation/entities").then().statusCode(400)+ .body("message", equalTo("The page size must be between 1 and 1000"));+ }++ @Test+ @Order(12)+ void updateStatus_reinstatedAndEnabledBecomeTheAggregate() {+ for (String status : new String[] {"REINSTATED", "ENABLED"}) {+ v2().body("{\"SendingStatus\":\"" + status + "\"}")+ .when().put(entityPath("RESOURCE", arnA) + "/customer-managed-status").then().statusCode(200);+ v2().when().get(entityPath("RESOURCE", arnA)).then().statusCode(200)+ .body("ReputationEntity.CustomerManagedStatus.Status", equalTo(status))+ .body("ReputationEntity.SendingStatusAggregate", equalTo(status));+ }+ }++ @Test+ @Order(13)+ void deleteTenant_removesTheEntity() {+ v2().body("{\"TenantName\":\"floci-rep-it-b\"}")+ .when().post("/v2/email/tenants/delete").then().statusCode(200);+ v2().when().get(entityPath("RESOURCE", arnB)).then().statusCode(400)+ .body("message", equalTo("ReputationEntity <" + arnB + "> does not exist"));+ v2().body("{\"TenantName\":\"floci-rep-it-a\"}")+ .when().post("/v2/email/tenants/delete").then().statusCode(200);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendNullAddressIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendNullAddressIntegrationTest.javaindex 739aec001d..fd20c688af 100644--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesSendNullAddressIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesSendNullAddressIntegrationTest.java@@ -86,6 +86,16 @@ class SesSendNullAddressIntegrationTest {.body("message", equalTo(NULL_ADDRESS));}+ @Test+ void sendBulkEmail_onlyEmptyDestinationsInTheRequest_answerEmptyDestination() {+ bulk("", entry("{}") + ", " + entry("{\"ToAddresses\": [], \"CcAddresses\": [null]}"))+ .statusCode(200)+ .body("BulkEmailEntryResults[0].Status", equalTo("INVALID_PARAMETER"))+ .body("BulkEmailEntryResults[0].Error", equalTo(EMPTY_DESTINATION))+ .body("BulkEmailEntryResults[1].Status", equalTo("INVALID_PARAMETER"))+ .body("BulkEmailEntryResults[1].Error", equalTo(EMPTY_DESTINATION));+ }+@Testvoid sendBulkEmail_onlyNullRecipientsInTheRequest_answerEmptyDestination() {bulk("", entry("{\"ToAddresses\": [null]}") + ", " + entry("{\"ToAddresses\": [null]}"))diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantListFilterServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantListFilterServiceTest.javaindex 7bc841aa75..05a757f0fb 100644--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantListFilterServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantListFilterServiceTest.java@@ -38,7 +38,7 @@ class SesTenantListFilterServiceTest {service.createTenant(name, List.of(), ACCOUNT, REGION);}tenantStore.put("tenant::" + REGION + "::other-FILTER-gamma", new Tenant("other-FILTER-gamma",- "tn-gamma", "arn", Instant.now(), List.of(), "DISABLED", null));+ "tn-gamma", "arn", Instant.now(), List.of(), "DISABLED", null, null, null));}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantSendV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantSendV2IntegrationTest.javaindex db83f5abd7..8bde0e569b 100644--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantSendV2IntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesTenantSendV2IntegrationTest.java@@ -6,6 +6,7 @@ import org.junit.jupiter.api.Order;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestMethodOrder;+import java.net.URLEncoder;import java.nio.charset.StandardCharsets;import java.util.Base64;@@ -20,8 +21,8 @@ import static org.hamcrest.Matchers.notNullValue;* the From identity (exact-address precedence included) and the configuration set; the* stored-template gate is inferred from the association model, not observed. The send-path* tenant-not-found wording differs from the management operations (no angle brackets, account id- * included, probe-confirmed). The tenant's SendingStatus is not checked — nothing can move it off- * ENABLED in the emulator.+ * included, probe-confirmed). A tenant whose customer-managed status is DISABLED is refused with a+ * 400 {@code MessageRejected} (probe-confirmed for the simple, templated, raw and bulk sends).*/@QuarkusTest@TestMethodOrder(MethodOrderer.OrderAnnotation.class)@@ -266,6 +267,23 @@ class SesTenantSendV2IntegrationTest {.when().post("/v2/email/outbound-bulk-emails").then().statusCode(404).body("message", equalTo("Tenant ghost-tenant for AwsAccountId 000000000000 not found."));+ // The tenant is looked up before the stored template...+ v2().body("{\"FromEmailAddress\":\"" + FROM + "\",\"TenantName\":\"ghost-tenant\","+ + "\"DefaultContent\":{\"Template\":{\"TemplateName\":\"ghost-template\","+ + "\"TemplateData\":\"{}\"}},"+ + "\"BulkEmailEntries\":[{\"Destination\":{\"ToAddresses\":"+ + "[\"[email protected]\"]}}]}")+ .when().post("/v2/email/outbound-bulk-emails").then().statusCode(404)+ .body("message", equalTo(+ "Tenant ghost-tenant for AwsAccountId 000000000000 not found."));+ // ...but not at all when no entry names a recipient: each entry is answered instead.+ v2().body("{\"FromEmailAddress\":\"" + FROM + "\",\"TenantName\":\"ghost-tenant\","+ + "\"DefaultContent\":{\"Template\":{\"TemplateName\":\"" + TEMPLATE + "\","+ + "\"TemplateData\":\"{}\"}},"+ + "\"BulkEmailEntries\":[{\"Destination\":{}}]}")+ .when().post("/v2/email/outbound-bulk-emails").then().statusCode(200)+ .body("BulkEmailEntryResults[0].Status", equalTo("INVALID_PARAMETER"))+ .body("BulkEmailEntryResults[0].Error", equalTo("Destination cannot be empty"));}@Test@@ -282,6 +300,96 @@ class SesTenantSendV2IntegrationTest {@Test@Order(12)+ void send_disabledTenant_isRejectedBeforeAssociationAndVerification() {+ String tenantArn = v2().body("{\"TenantName\":\"" + TENANT + "\"}")+ .when().post("/v2/email/tenants/get").then().statusCode(200)+ .extract().path("Tenant.TenantArn");+ String disabled = "Sending disabled for <" + tenantArn+ + ">. For more information, please check the resource configuration and status.";+ setStatus(tenantArn, "DISABLED");++ v2().body(simpleSend(TENANT, ""))+ .when().post("/v2/email/outbound-emails").then().statusCode(400)+ .body("__type", equalTo("MessageRejected"))+ .body("message", equalTo(disabled));+ v2().body("{\"FromEmailAddress\":\"" + FROM + "\",\"TenantName\":\"" + TENANT + "\","+ + "\"DefaultContent\":{\"Template\":{\"TemplateName\":\"" + TEMPLATE + "\","+ + "\"TemplateData\":\"{}\"}},"+ + "\"BulkEmailEntries\":[{\"Destination\":{\"ToAddresses\":"+ + "[\"[email protected]\"]}}]}")+ .when().post("/v2/email/outbound-bulk-emails").then().statusCode(400)+ .body("__type", equalTo("MessageRejected"))+ .body("message", equalTo(disabled));+ // A malformed address and a send with no recipient are reported ahead of the refusal...+ v2().body("{\"FromEmailAddress\":\"" + FROM + "\",\"TenantName\":\"" + TENANT + "\","+ + "\"Content\":{\"Simple\":{\"Subject\":{\"Data\":\"s\"},"+ + "\"Body\":{\"Text\":{\"Data\":\"t\"}}}}}")+ .when().post("/v2/email/outbound-emails").then().statusCode(400)+ .body("__type", equalTo("BadRequestException"))+ .body("message", equalTo("At least one destination address is required."));+ v2().body(simpleSend(TENANT, "").replace(FROM, "not an address"))+ .when().post("/v2/email/outbound-emails").then().statusCode(400)+ .body("__type", equalTo("BadRequestException"))+ .body("message", equalTo("Local address contains control or whitespace"));+ // ...while a raw message with no recipient anywhere is refused before its missing To header...+ String noRecipients = Base64.getEncoder().encodeToString(+ ("From: " + FROM + "\r\nSubject: s\r\n\r\nbody\r\n").getBytes(StandardCharsets.UTF_8));+ v2().body("{\"TenantName\":\"" + TENANT + "\",\"Content\":{\"Raw\":{\"Data\":\"" + noRecipients + "\"}}}")+ .when().post("/v2/email/outbound-emails").then().statusCode(400)+ .body("__type", equalTo("MessageRejected"))+ .body("message", equalTo(disabled));+ // ...and an unverified sender and an unassociated identity both lose to the refusal...+ v2().body(simpleSend(TENANT, "").replace(FROM, "[email protected]"))+ .when().post("/v2/email/outbound-emails").then().statusCode(400)+ .body("__type", equalTo("MessageRejected"));+ // ...while an unknown configuration set still wins over it, except on a bulk send.+ v2().body(simpleSend(TENANT, "\"ConfigurationSetName\":\"ghost-cs\","))+ .when().post("/v2/email/outbound-emails").then().statusCode(404)+ .body("__type", equalTo("NotFoundException"))+ .body("message", equalTo("Configuration set <ghost-cs> does not exist."));+ v2().body("{\"FromEmailAddress\":\"" + FROM + "\",\"TenantName\":\"" + TENANT + "\","+ + "\"ConfigurationSetName\":\"ghost-cs\","+ + "\"DefaultContent\":{\"Template\":{\"TemplateName\":\"" + TEMPLATE + "\","+ + "\"TemplateData\":\"{}\"}},"+ + "\"BulkEmailEntries\":[{\"Destination\":{\"ToAddresses\":"+ + "[\"[email protected]\"]}}]}")+ .when().post("/v2/email/outbound-bulk-emails").then().statusCode(400)+ .body("__type", equalTo("MessageRejected"))+ .body("message", equalTo(disabled));+ // A bulk send meets the refusal before an unknown stored template, and skips it when no+ // entry names a recipient.+ v2().body("{\"FromEmailAddress\":\"" + FROM + "\",\"TenantName\":\"" + TENANT + "\","+ + "\"DefaultContent\":{\"Template\":{\"TemplateName\":\"ghost-template\","+ + "\"TemplateData\":\"{}\"}},"+ + "\"BulkEmailEntries\":[{\"Destination\":{\"ToAddresses\":"+ + "[\"[email protected]\"]}}]}")+ .when().post("/v2/email/outbound-bulk-emails").then().statusCode(400)+ .body("__type", equalTo("MessageRejected"))+ .body("message", equalTo(disabled));+ v2().body("{\"FromEmailAddress\":\"" + FROM + "\",\"TenantName\":\"" + TENANT + "\","+ + "\"DefaultContent\":{\"Template\":{\"TemplateName\":\"" + TEMPLATE + "\","+ + "\"TemplateData\":\"{}\"}},"+ + "\"BulkEmailEntries\":[{\"Destination\":{\"ToAddresses\":[]}}]}")+ .when().post("/v2/email/outbound-bulk-emails").then().statusCode(200)+ .body("BulkEmailEntryResults[0].Status", equalTo("INVALID_PARAMETER"))+ .body("BulkEmailEntryResults[0].Error", equalTo("Destination cannot be empty"));++ setStatus(tenantArn, "REINSTATED");+ v2().body(simpleSend(TENANT, ""))+ .when().post("/v2/email/outbound-emails").then().statusCode(200)+ .body("MessageId", notNullValue());+ setStatus(tenantArn, "ENABLED");+ }++ private static void setStatus(String tenantArn, String status) {+ v2().urlEncodingEnabled(false).body("{\"SendingStatus\":\"" + status + "\"}")+ .when().put("/v2/email/reputation/entities/RESOURCE/"+ + URLEncoder.encode(tenantArn, StandardCharsets.UTF_8) + "/customer-managed-status")+ .then().statusCode(200);+ }++ @Test+ @Order(13)void cleanup_cascadeAndResources() {v2().body("{\"TenantName\":\"" + TENANT + "\"}").when().post("/v2/email/tenants/delete").then().statusCode(200);diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesV2BodyReadIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2BodyReadIntegrationTest.javaindex 8c2bfeed3a..6533cba1b9 100644--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesV2BodyReadIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2BodyReadIntegrationTest.java@@ -25,6 +25,7 @@ import static org.hamcrest.Matchers.notNullValue;class SesV2BodyReadIntegrationTest {private static final String IDENTITY = "/v2/email/identities/body-read-ghost.example.com";+ private static final String REPUTATION_ENTITY = "/v2/email/reputation/entities/RESOURCE/body-read-ghost";private static final List<Arguments> ENDPOINTS = List.of(Arguments.of("POST", "/v2/email/tenants/list"),@@ -44,7 +45,10 @@ class SesV2BodyReadIntegrationTest {Arguments.of("POST", "/v2/email/outbound-emails"),Arguments.of("POST", "/v2/email/dedicated-ip-pools"),Arguments.of("PUT", "/v2/email/suppression/addresses"),- Arguments.of("POST", "/v2/email/tags"));+ Arguments.of("POST", "/v2/email/tags"),+ Arguments.of("POST", "/v2/email/reputation/entities"),+ Arguments.of("PUT", REPUTATION_ENTITY + "/policy"),+ Arguments.of("PUT", REPUTATION_ENTITY + "/customer-managed-status"));static Stream<Arguments> malformedBodyCases() {return ENDPOINTS.stream().flatMap(endpoint -> Stream.of("{", "{\"a\":}", "{} x", "{}{}")