feat(ses): support v2 tenant resource associations (#2710)

* feat(ses): support v2 tenant resource associations

* fix(ses): reject nameless association ARNs and stop key-suffix resource matching
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-08-29 14:29:36 -04:00
1 parent 2a7c94b04d
commit 67f75c7e1d
9 files changed
+1106 -23

No files matched your search

@@ -11,49 +11,75 @@ import org.junit.jupiter.api.TestMethodOrder;
import software.amazon.awssdk.services.sesv2.SesV2Client;
import software.amazon.awssdk.services.sesv2.model.AlreadyExistsException;
import software.amazon.awssdk.services.sesv2.model.BadRequestException;
import software.amazon.awssdk.services.sesv2.model.CreateConfigurationSetRequest;
import software.amazon.awssdk.services.sesv2.model.CreateEmailIdentityRequest;
import software.amazon.awssdk.services.sesv2.model.CreateTenantRequest;
import software.amazon.awssdk.services.sesv2.model.CreateTenantResponse;
import software.amazon.awssdk.services.sesv2.model.DeleteConfigurationSetRequest;
import software.amazon.awssdk.services.sesv2.model.DeleteEmailIdentityRequest;
import software.amazon.awssdk.services.sesv2.model.DeleteTenantRequest;
import software.amazon.awssdk.services.sesv2.model.DeleteTenantResourceAssociationRequest;
import software.amazon.awssdk.services.sesv2.model.GetTenantRequest;
import software.amazon.awssdk.services.sesv2.model.GetTenantResponse;
import software.amazon.awssdk.services.sesv2.model.ListResourceTenantsRequest;
import software.amazon.awssdk.services.sesv2.model.ListResourceTenantsResponse;
import software.amazon.awssdk.services.sesv2.model.ListTenantResourcesFilterKey;
import software.amazon.awssdk.services.sesv2.model.ListTenantResourcesRequest;
import software.amazon.awssdk.services.sesv2.model.ListTenantResourcesResponse;
import software.amazon.awssdk.services.sesv2.model.ListTenantsRequest;
import software.amazon.awssdk.services.sesv2.model.ListTenantsResponse;
import software.amazon.awssdk.services.sesv2.model.NotFoundException;
import software.amazon.awssdk.services.sesv2.model.Tag;
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 tenant APIs. Verifies the AWS Java SDK v2 marshalling of
* CreateTenant / GetTenant / ListTenants / DeleteTenant — the RPC-style POST routes, the generated
* TenantId (tn-) and TenantArn, the ENABLED sending status, and the
* AlreadyExistsException / NotFoundException / BadRequestException errors — against a live Floci
* instance. Tenants are reversible (create + delete), so cleanup restores the account.
* SDK compatibility test for the SES v2 tenant APIs: the CRUD (CreateTenant / GetTenant /
* ListTenants / DeleteTenant) and the resource associations (CreateTenantResourceAssociation /
* DeleteTenantResourceAssociation / ListTenantResources / ListResourceTenants), one ordered flow
* against a live Floci instance. One AWS quirk drives the association assertions: the service's wire
* values for ResourceType — in responses and as the RESOURCE_TYPE filter value — are the ARN
* segments (identity / configuration-set / template), not the SDK's EMAIL_IDENTITY-style enum
* constants. Real AWS rejects the enum spelling as a filter and returns values the SDK maps to
* UNKNOWN_TO_SDK_VERSION, so the test asserts resourceTypeAsString. Tenants are reversible
* (create + delete), so cleanup restores the account.
*/
@DisplayName("SES v2 Tenants")
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SesTenantTest {
private static final String TENANT = "compat-tenant-alpha";
private static final String IDENTITY = "compat-assoc.example.com";
private static final String CONFIG_SET = "compat-assoc-cs";
private static SesV2Client sesV2;
private static String identityArn;
private static String configSetArn;
@BeforeAll
static void setup() {
sesV2 = TestFixtures.sesV2Client();
sesV2.createEmailIdentity(CreateEmailIdentityRequest.builder().emailIdentity(IDENTITY).build());
sesV2.createConfigurationSet(CreateConfigurationSetRequest.builder()
.configurationSetName(CONFIG_SET).build());
}
@AfterAll
static void cleanup() {
if (sesV2 != null) {
try {
// DeleteTenant cascades any remaining associations, freeing the backing resources.
sesV2.deleteTenant(DeleteTenantRequest.builder().tenantName(TENANT).build());
} catch (NotFoundException expected) {
// Already removed by the delete test; anything else (auth, connectivity) must surface.
} finally {
sesV2.close();
}
sesV2.deleteConfigurationSet(DeleteConfigurationSetRequest.builder()
.configurationSetName(CONFIG_SET).build());
sesV2.deleteEmailIdentity(DeleteEmailIdentityRequest.builder().emailIdentity(IDENTITY).build());
sesV2.close();
}
}
@@ -70,6 +96,10 @@ class SesTenantTest {
assertThat(resp.sendingStatusAsString()).isEqualTo("ENABLED");
assertThat(resp.createdTimestamp()).isNotNull();
assertThat(resp.tags()).extracting(Tag::key).contains("team");
String arnPrefix = resp.tenantArn().substring(0, resp.tenantArn().indexOf(":tenant/") + 1);
identityArn = arnPrefix + "identity/" + IDENTITY;
configSetArn = arnPrefix + "configuration-set/" + CONFIG_SET;
}
@Test
@@ -107,14 +137,118 @@ class SesTenantTest {
@Test
@Order(6)
void deleteTenant_removesIt_thenGetIsNotFound() {
void createAssociations_succeed() {
sesV2.createTenantResourceAssociation(r -> r.tenantName(TENANT).resourceArn(identityArn));
sesV2.createTenantResourceAssociation(r -> r.tenantName(TENANT).resourceArn(configSetArn));
}
@Test
@Order(7)
void createAssociation_duplicate_throwsAlreadyExists() {
assertThatThrownBy(() -> sesV2.createTenantResourceAssociation(
r -> r.tenantName(TENANT).resourceArn(identityArn)))
.isInstanceOf(AlreadyExistsException.class)
.hasMessageContaining("has already been associated with tenant " + TENANT);
}
@Test
@Order(8)
void createAssociation_missingTenantOrResource_throwsNotFound() {
assertThatThrownBy(() -> sesV2.createTenantResourceAssociation(
r -> r.tenantName("compat-assoc-ghost").resourceArn(identityArn)))
.isInstanceOf(NotFoundException.class);
assertThatThrownBy(() -> sesV2.createTenantResourceAssociation(
r -> r.tenantName(TENANT).resourceArn(configSetArn.replace(CONFIG_SET, "ghost-cs"))))
.isInstanceOf(NotFoundException.class)
.hasMessageContaining("Configuration set <ghost-cs> does not exist:");
}
@Test
@Order(9)
void createAssociation_invalidArn_throwsBadRequest() {
assertThatThrownBy(() -> sesV2.createTenantResourceAssociation(
r -> r.tenantName(TENANT).resourceArn("not-an-arn")))
.isInstanceOf(BadRequestException.class)
.hasMessageContaining("Provided resource identifier is not an SES resource");
}
@Test
@Order(10)
void listTenantResources_returnsArnSegmentTypeValues() {
ListTenantResourcesResponse resp = sesV2.listTenantResources(
ListTenantResourcesRequest.builder().tenantName(TENANT).build());
assertThat(resp.tenantResources()).hasSize(2);
// Sorted by ARN; the wire type values do not map onto the SDK enum.
assertThat(resp.tenantResources().get(0).resourceTypeAsString()).isEqualTo("configuration-set");
assertThat(resp.tenantResources().get(1).resourceTypeAsString()).isEqualTo("identity");
assertThat(resp.tenantResources().get(1).resourceArn()).isEqualTo(identityArn);
}
@Test
@Order(11)
void listTenantResources_filterTakesWireValues_rejectsEnumSpelling() {
ListTenantResourcesResponse filtered = sesV2.listTenantResources(
ListTenantResourcesRequest.builder().tenantName(TENANT)
.filter(Map.of(ListTenantResourcesFilterKey.RESOURCE_TYPE, "identity"))
.build());
assertThat(filtered.tenantResources()).hasSize(1);
assertThat(filtered.tenantResources().get(0).resourceArn()).isEqualTo(identityArn);
assertThatThrownBy(() -> sesV2.listTenantResources(
ListTenantResourcesRequest.builder().tenantName(TENANT)
.filter(Map.of(ListTenantResourcesFilterKey.RESOURCE_TYPE, "EMAIL_IDENTITY"))
.build()))
.isInstanceOf(BadRequestException.class)
.hasMessageContaining("Invalid resource type EMAIL_IDENTITY specified.");
}
@Test
@Order(12)
void listResourceTenants_returnsAssociationMetadata() {
ListResourceTenantsResponse resp = sesV2.listResourceTenants(
ListResourceTenantsRequest.builder().resourceArn(identityArn).build());
assertThat(resp.resourceTenants()).hasSize(1);
assertThat(resp.resourceTenants().get(0).tenantName()).isEqualTo(TENANT);
assertThat(resp.resourceTenants().get(0).tenantId()).startsWith("tn-");
assertThat(resp.resourceTenants().get(0).resourceArn()).isEqualTo(identityArn);
assertThat(resp.resourceTenants().get(0).associatedTimestamp()).isNotNull();
}
@Test
@Order(13)
void deleteBackingResource_whileAssociated_isBlocked() {
assertThatThrownBy(() -> sesV2.deleteConfigurationSet(DeleteConfigurationSetRequest.builder()
.configurationSetName(CONFIG_SET).build()))
.isInstanceOf(BadRequestException.class)
.hasMessageContaining("because it has tenant associations");
}
@Test
@Order(14)
void deleteAssociation_removesIt_andIsIdempotent() {
sesV2.deleteTenantResourceAssociation(DeleteTenantResourceAssociationRequest.builder()
.tenantName(TENANT).resourceArn(configSetArn).build());
// Removing an association that no longer exists is a silent success on AWS.
sesV2.deleteTenantResourceAssociation(DeleteTenantResourceAssociationRequest.builder()
.tenantName(TENANT).resourceArn(configSetArn).build());
ListTenantResourcesResponse resp = sesV2.listTenantResources(
ListTenantResourcesRequest.builder().tenantName(TENANT).build());
assertThat(resp.tenantResources()).hasSize(1);
}
@Test
@Order(15)
void deleteTenant_cascadesRemainingAssociations_thenGetIsNotFound() {
sesV2.deleteTenant(DeleteTenantRequest.builder().tenantName(TENANT).build());
ListResourceTenantsResponse resp = sesV2.listResourceTenants(
ListResourceTenantsRequest.builder().resourceArn(identityArn).build());
assertThat(resp.resourceTenants()).isEmpty();
assertThatThrownBy(() -> sesV2.getTenant(GetTenantRequest.builder().tenantName(TENANT).build()))
.isInstanceOf(NotFoundException.class);
}
@Test
@Order(7)
@Order(16)
void deleteTenant_missing_throwsNotFound() {
assertThatThrownBy(() -> sesV2.deleteTenant(DeleteTenantRequest.builder()
.tenantName("compat-tenant-does-not-exist").build()))
+7 -1
View File
@@ -214,6 +214,10 @@ Alongside the classic Query API, Floci implements a subset of the SES v2 REST JS
| `POST` | `/v2/email/tenants/get` | `GetTenant` |
| `POST` | `/v2/email/tenants/list` | `ListTenants` |
| `POST` | `/v2/email/tenants/delete` | `DeleteTenant` |
| `POST` | `/v2/email/tenants/resources` | `CreateTenantResourceAssociation` |
| `POST` | `/v2/email/tenants/resources/delete` | `DeleteTenantResourceAssociation` |
| `POST` | `/v2/email/tenants/resources/list` | `ListTenantResources` |
| `POST` | `/v2/email/resources/tenants/list` | `ListResourceTenants` |
| `POST` | `/v2/email/templates` | `CreateEmailTemplate` |
| `GET` | `/v2/email/templates` | `ListEmailTemplates` |
| `GET` | `/v2/email/templates/{templateName}` | `GetEmailTemplate` |
@@ -284,7 +288,9 @@ Account-level VDM (Virtual Deliverability Manager) attributes are stored per reg
Account provisioning details are stored per region. `PutAccountDetails` sets `MailType` (required, ∈ {`MARKETING`, `TRANSACTIONAL`}) and `WebsiteURL` (required, 1–1000 chars) plus the optional `ContactLanguage` (∈ {`EN`, `JA`}), `UseCaseDescription` (≤5000 chars), `AdditionalContactEmailAddresses` (1–4 entries, each 6–254 chars matching `^(.+)@(.+)$`), and `ProductionAccessEnabled`. Floci stores `ProductionAccessEnabled` as given but stays production-enabled regardless (it has no sandbox), so the flag has no functional effect. Like `VdmAttributes`, `GetAccount` omits `Details` until it has been configured for the region, then echoes the stored fields under `Details` with a `ReviewDetails` block. Matching AWS, all modeled-constraint violations (null / enum / length / list) are aggregated into a single `BadRequestException` reporting every failure; a malformed (but in-range) `WebsiteURL` is reported separately as `Url contains invalid format`. Floci has no sandbox and does not run a production-access review, so `ReviewDetails.Status` is always `GRANTED`.
Tenants (multi-tenancy) are stored per region. `CreateTenant` requires a `TenantName` (1–64 chars, `[A-Za-z0-9_-]`) and accepts optional `Tags`; it returns the tenant with a generated `TenantId` (`tn-` + 30 hex), a `TenantArn` (`arn:aws:ses:<region>:<account>:tenant/<name>/<id>`), a `CreatedTimestamp`, and `SendingStatus` `ENABLED`. The operations use RPC-style POST subpaths (`/tenants/get`, `/tenants/list`, `/tenants/delete`); `ListTenants` returns the `TenantInfo` subset (no `Tags`/`SendingStatus`) and currently returns every tenant in a single page — `PageSize`/`NextToken` pagination is not yet implemented. A duplicate name is `AlreadyExistsException`; an unknown tenant on get/delete is `NotFoundException`. Resource associations, tenant suppression, and tenant-scoped sending are not yet implemented.
Tenants (multi-tenancy) are stored per region. `CreateTenant` requires a `TenantName` (1–64 chars, `[A-Za-z0-9_-]`) and accepts optional `Tags`; it returns the tenant with a generated `TenantId` (`tn-` + 30 hex), a `TenantArn` (`arn:aws:ses:<region>:<account>:tenant/<name>/<id>`), a `CreatedTimestamp`, and `SendingStatus` `ENABLED`. The operations use RPC-style POST subpaths (`/tenants/get`, `/tenants/list`, `/tenants/delete`); `ListTenants` returns the `TenantInfo` subset (no `Tags`/`SendingStatus`) and currently returns every tenant in a single page — `PageSize`/`NextToken` pagination is not yet implemented. A duplicate name is `AlreadyExistsException`; an unknown tenant on get/delete is `NotFoundException`.
Tenant resource associations link a tenant to email identities, configuration sets, and email templates. Matching real AWS, the wire values for `ResourceType` — in responses and as the `Filter` `RESOURCE_TYPE` value — are the ARN segments `identity` / `configuration-set` / `template`; the SDK's `EMAIL_IDENTITY`-style enum constants are rejected, as AWS itself does. The resource must exist in the same account and region; a duplicate association is `AlreadyExistsException`, and deleting a missing one succeeds silently. Deleting a resource that still has associations is rejected, while `DeleteTenant` cascades its associations away. The list operations return a single page (no `PageSize`/`NextToken` pagination yet, like `ListTenants`); tenant suppression and tenant-scoped sending are not yet implemented.
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).
@@ -27,6 +27,7 @@ import io.github.hectorvent.floci.services.ses.model.SuppressedDestination;
import io.github.hectorvent.floci.services.ses.model.SuppressionOptions;
import io.github.hectorvent.floci.services.ses.model.Tag;
import io.github.hectorvent.floci.services.ses.model.Tenant;
import io.github.hectorvent.floci.services.ses.model.TenantResourceAssociation;
import io.github.hectorvent.floci.services.ses.model.TrackingOptions;
import io.github.hectorvent.floci.services.ses.model.VdmOptions;
import com.fasterxml.jackson.databind.JsonNode;
@@ -945,6 +946,126 @@ public class SesController {
}
}
// Phase 2: tenant→resource associations. AWS's wire format for ResourceType — in responses and as
// the RESOURCE_TYPE filter value — is the ARN segment (identity / configuration-set / template),
// not the SDK's EMAIL_IDENTITY-style enum spelling; real AWS rejects the enum spelling.
@POST
@Path("/tenants/resources")
public Response createTenantResourceAssociation(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
JsonNode request = (body == null || body.isBlank())
? objectMapper.createObjectNode()
: objectMapper.readTree(body);
requireJsonObject(request);
String tenantName = stringMemberOrAbsent(request, "TenantName");
String resourceArn = stringMemberOrAbsent(request, "ResourceArn");
sesService.createTenantResourceAssociation(tenantName, resourceArn,
regionResolver.getAccountId(), region);
return Response.ok(objectMapper.createObjectNode()).build();
} catch (AwsException e) {
throw remapV1Exception(e);
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
throw new AwsException("SerializationException", null, 400);
}
}
@POST
@Path("/tenants/resources/delete")
public Response deleteTenantResourceAssociation(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
JsonNode request = (body == null || body.isBlank())
? objectMapper.createObjectNode()
: objectMapper.readTree(body);
requireJsonObject(request);
String tenantName = stringMemberOrAbsent(request, "TenantName");
String resourceArn = stringMemberOrAbsent(request, "ResourceArn");
sesService.deleteTenantResourceAssociation(tenantName, resourceArn,
regionResolver.getAccountId(), region);
return Response.ok(objectMapper.createObjectNode()).build();
} catch (AwsException e) {
throw remapV1Exception(e);
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
throw new AwsException("SerializationException", null, 400);
}
}
@POST
@Path("/tenants/resources/list")
public Response listTenantResources(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
JsonNode request = (body == null || body.isBlank())
? objectMapper.createObjectNode()
: objectMapper.readTree(body);
requireJsonObject(request);
String tenantName = stringMemberOrAbsent(request, "TenantName");
String resourceTypeFilter = null;
JsonNode filter = request.path("Filter");
if (!filter.isMissingNode() && !filter.isNull()) {
if (!filter.isObject()) {
throw new AwsException("SerializationException", null, 400);
}
resourceTypeFilter = stringMemberOrAbsent(filter, "RESOURCE_TYPE");
}
Integer pageSize = intMemberOrAbsent(request, "PageSize");
String nextToken = stringMemberOrAbsent(request, "NextToken");
List<TenantResourceAssociation> associations = sesService.listTenantResources(
tenantName, resourceTypeFilter, pageSize, nextToken, region);
ObjectNode result = objectMapper.createObjectNode();
// AWS renders NextToken as an explicit null on the last (here: only) page.
result.putNull("NextToken");
ArrayNode resources = result.putArray("TenantResources");
for (TenantResourceAssociation a : associations) {
ObjectNode item = resources.addObject();
item.put("ResourceArn", a.resourceArn());
item.put("ResourceType", a.resourceType());
}
return Response.ok(result).build();
} catch (AwsException e) {
throw remapV1Exception(e);
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
throw new AwsException("SerializationException", null, 400);
}
}
@POST
@Path("/resources/tenants/list")
public Response listResourceTenants(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
JsonNode request = (body == null || body.isBlank())
? objectMapper.createObjectNode()
: objectMapper.readTree(body);
requireJsonObject(request);
String resourceArn = stringMemberOrAbsent(request, "ResourceArn");
Integer pageSize = intMemberOrAbsent(request, "PageSize");
String nextToken = stringMemberOrAbsent(request, "NextToken");
List<TenantResourceAssociation> associations = sesService.listResourceTenants(
resourceArn, pageSize, nextToken, regionResolver.getAccountId(), region);
ObjectNode result = objectMapper.createObjectNode();
result.putNull("NextToken");
ArrayNode tenants = result.putArray("ResourceTenants");
for (TenantResourceAssociation a : associations) {
// ResourceTenantMetadata has no TenantArn (probe-confirmed).
ObjectNode item = tenants.addObject();
item.put("TenantName", a.tenantName());
item.put("TenantId", a.tenantId());
item.put("ResourceArn", a.resourceArn());
if (a.associatedTimestamp() != null) {
item.put("AssociatedTimestamp", a.associatedTimestamp().toEpochMilli() / 1000.0);
}
}
return Response.ok(result).build();
} catch (AwsException e) {
throw remapV1Exception(e);
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
throw new AwsException("SerializationException", null, 400);
}
}
// Read a typed string member: absent/null returns null, but a present value of the wrong JSON type
// is rejected rather than coerced (asText would turn 123 into "123"), matching AWS.
private static String stringMemberOrAbsent(JsonNode parent, String field) {
@@ -2141,6 +2262,20 @@ public class SesController {
return n.textValue();
}
// Integer variant of stringMemberOrAbsent: absent/null returns null, non-integral JSON is
// rejected rather than coerced, and so is an integral value outside the int range (intValue
// would silently truncate it).
private static Integer intMemberOrAbsent(JsonNode parent, String field) {
JsonNode n = parent.path(field);
if (n.isMissingNode() || n.isNull()) {
return null;
}
if (!n.isIntegralNumber() || !n.canConvertToInt()) {
throw new AwsException("SerializationException", null, 400);
}
return n.intValue();
}
// Parse an AWS FeatureStatus (ENABLED/DISABLED) field. A required member that is absent, or any
// value outside the enum, is a Smithy BadRequestException the way AWS returns it; an absent
// optional member defaults to DISABLED (false).
@@ -36,6 +36,7 @@ import io.github.hectorvent.floci.services.ses.model.TrackingOptions;
import io.github.hectorvent.floci.services.ses.model.VdmOptions;
import io.github.hectorvent.floci.services.ses.model.SentEmail;
import io.github.hectorvent.floci.services.ses.model.Tenant;
import io.github.hectorvent.floci.services.ses.model.TenantResourceAssociation;
import io.github.hectorvent.floci.services.ses.model.SuppressedDestination;
import io.github.hectorvent.floci.services.ses.model.SuppressionOptions;
import io.github.hectorvent.floci.services.ses.model.Tag;
@@ -260,6 +261,11 @@ public class SesService {
if (identityValue == null || identityValue.isBlank()) {
return;
}
tenantService.deleteBackingResource(SesTenantService.RESOURCE_TYPE_IDENTITY, identityValue,
region, () -> doDeleteIdentity(identityValue, region));
}
private void doDeleteIdentity(String identityValue, String region) {
String key = identityKey(region, identityValue);
identityStore.delete(key);
invalidateDkimLookupCache(region, identityValue);
@@ -1185,7 +1191,8 @@ public class SesService {
}
public void deleteTemplate(String templateName, String region) {
templateService.deleteTemplate(templateName, region);
tenantService.deleteBackingResource(SesTenantService.RESOURCE_TYPE_TEMPLATE, templateName,
region, () -> templateService.deleteTemplate(templateName, region));
}
public List<EmailTemplate> listTemplates(String region) {
@@ -1634,8 +1641,11 @@ public class SesService {
throw new AwsException("ConfigurationSetDoesNotExist",
"Configuration set <" + name + "> does not exist.", 400);
}
configSetStore.delete(key);
LOG.infov("Deleted SES configuration set: {0} in region {1}", name, region);
tenantService.deleteBackingResource(SesTenantService.RESOURCE_TYPE_CONFIGURATION_SET, name,
region, () -> {
configSetStore.delete(key);
LOG.infov("Deleted SES configuration set: {0} in region {1}", name, region);
});
}
private static final Pattern CONFIG_SET_NAME = Pattern.compile("^[A-Za-z0-9_-]{1,64}$");
@@ -1664,6 +1674,77 @@ public class SesService {
tenantService.deleteTenant(tenantName, region);
}
// The association operations validate resource existence here in the facade — the tenant domain
// owns the association store, but only this class can reach the identity/configuration-set/template
// stores without a service→service dependency.
public void createTenantResourceAssociation(String tenantName, String resourceArn,
String accountId, String region) {
SesTenantService.AssociationResource ref =
SesTenantService.parseResourceArn(resourceArn, accountId, region);
Tenant tenant = tenantService.tenantForAssociation(tenantName, region);
// The existence check runs inside the association lock so it stays atomic with the
// backing-resource delete guards.
tenantService.associate(tenant, ref, region, () -> requireTenantResourceExists(ref, region));
}
public void deleteTenantResourceAssociation(String tenantName, String resourceArn,
String accountId, String region) {
SesTenantService.AssociationResource ref =
SesTenantService.parseResourceArn(resourceArn, accountId, region);
Tenant tenant = tenantService.tenantForAssociation(tenantName, region);
// AWS still 404s on a missing resource even though removing a missing association succeeds.
requireTenantResourceExists(ref, region);
tenantService.disassociate(tenant, ref, region);
}
public List<TenantResourceAssociation> listTenantResources(String tenantName,
String resourceTypeFilter,
Integer pageSize, String nextToken,
String region) {
SesTenantService.validateListPaging(pageSize, nextToken);
SesTenantService.validateResourceTypeFilter(resourceTypeFilter);
Tenant tenant = tenantService.tenantForAssociation(tenantName, region);
return tenantService.listTenantResources(tenant, resourceTypeFilter, region);
}
public List<TenantResourceAssociation> listResourceTenants(String resourceArn, Integer pageSize,
String nextToken, String accountId,
String region) {
SesTenantService.validateListPaging(pageSize, nextToken);
SesTenantService.AssociationResource ref =
SesTenantService.parseResourceArn(resourceArn, accountId, region);
requireTenantResourceExists(ref, region);
return tenantService.listResourceTenants(ref, region);
}
// The association APIs 404 with a per-type message when the referenced resource is missing; the
// trailing colon on the configuration-set variant is AWS's own.
private void requireTenantResourceExists(SesTenantService.AssociationResource ref, String region) {
boolean exists = switch (ref.type()) {
case SesTenantService.RESOURCE_TYPE_IDENTITY ->
identityStore.get(identityKey(region, ref.name())).isPresent();
case SesTenantService.RESOURCE_TYPE_CONFIGURATION_SET ->
CONFIG_SET_NAME.matcher(ref.name()).matches()
&& configSetStore.get(configSetKey(region, ref.name())).isPresent();
case SesTenantService.RESOURCE_TYPE_TEMPLATE ->
templateService.find(ref.name(), region).isPresent();
default -> false;
};
if (exists) {
return;
}
String message = switch (ref.type()) {
case SesTenantService.RESOURCE_TYPE_IDENTITY ->
"Identity <" + ref.name() + "> does not exist";
case SesTenantService.RESOURCE_TYPE_CONFIGURATION_SET ->
"Configuration set <" + ref.name() + "> does not exist:";
default -> "Email template <" + ref.name() + "> does not exist";
};
throw new AwsException("NotFoundException", message, 404);
}
// ──────────────────────── Receipt rule sets (inbound) ────────────────────────
//
// Receipt rule sets live in SesReceiptRuleService; this facade
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ses.model.Tag;
import io.github.hectorvent.floci.services.ses.model.Tenant;
import io.github.hectorvent.floci.services.ses.model.TenantResourceAssociation;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -28,8 +29,9 @@ import java.util.regex.Pattern;
* built here carry only region and tenant name. The caller's account is used for the ARN (and the
* AlreadyExists message), not the key.
*
* <p>This is Phase 1 (tenant CRUD); resource associations, tenant suppression, and tenant-scoped
* sending are separate follow-ups.
* <p>Phase 2 adds tenant→resource associations, owned here as well ({@code associationStore}); the
* facade validates that the referenced resource exists before delegating. Tenant suppression and
* tenant-scoped sending are separate follow-ups.
*/
@ApplicationScoped
public class SesTenantService {
@@ -40,7 +42,26 @@ public class SesTenantService {
private static final Pattern TENANT_NAME_CHARS = Pattern.compile("[A-Za-z0-9_-]+");
private static final char[] HEX = "0123456789abcdef".toCharArray();
// The wire values for ResourceType — the ARN segment, not the SDK enum spelling. Real AWS both
// returns these and requires them as Filter values; the SDK's EMAIL_IDENTITY-style enum constants
// are rejected by the service (probe-confirmed 2026-08-28).
static final String RESOURCE_TYPE_IDENTITY = "identity";
static final String RESOURCE_TYPE_CONFIGURATION_SET = "configuration-set";
static final String RESOURCE_TYPE_TEMPLATE = "template";
private static final List<String> SUPPORTED_RESOURCE_TYPES =
List.of(RESOURCE_TYPE_IDENTITY, RESOURCE_TYPE_CONFIGURATION_SET, RESOURCE_TYPE_TEMPLATE);
/**
* A parsed, format-validated SES resource ARN for the association operations; {@code type} is one
* of the wire resource types. Deliberately separate from the tag dispatch's {@code parseSesArn}
* in {@code SesService}: the association APIs have their own probe-confirmed error messages and
* validation precedence (type before region before account), so the parsers must not be merged.
*/
record AssociationResource(String type, String name, String arn) {
}
private final StorageBackend<String, Tenant> tenantStore;
private final StorageBackend<String, TenantResourceAssociation> associationStore;
private final Clock clock;
private final SecureRandom random;
// Serializes the per-name check-then-put so concurrent creates for the same tenant can't both
@@ -50,11 +71,17 @@ public class SesTenantService {
@Inject
public SesTenantService(StorageFactory storageFactory, Clock clock) {
this(storageFactory.create("ses", "ses-tenants.json",
new TypeReference<Map<String, Tenant>>() {}), clock, new SecureRandom());
new TypeReference<Map<String, Tenant>>() {}),
storageFactory.create("ses", "ses-tenant-associations.json",
new TypeReference<Map<String, TenantResourceAssociation>>() {}),
clock, new SecureRandom());
}
SesTenantService(StorageBackend<String, Tenant> tenantStore, Clock clock, SecureRandom random) {
SesTenantService(StorageBackend<String, Tenant> tenantStore,
StorageBackend<String, TenantResourceAssociation> associationStore,
Clock clock, SecureRandom random) {
this.tenantStore = tenantStore;
this.associationStore = associationStore;
this.clock = clock;
this.random = random;
}
@@ -101,8 +128,16 @@ public class SesTenantService {
validateTenantName(tenantName);
String key = tenantKey(region, tenantName);
synchronized (tenantMutationLock) {
if (tenantStore.get(key).isEmpty()) {
throw tenantNotFound(tenantName);
Tenant tenant = tenantStore.get(key).orElseThrow(() -> tenantNotFound(tenantName));
// AWS cascades: deleting a tenant silently removes its resource associations
// (probe-confirmed 2026-08-28). Keys carry the TenantId, so a recreated same-name tenant
// never sees the old associations. The associations go first — persistent/wal backends
// apply each deletion durably, so a crash mid-cascade must leave the tenant record (a
// retryable DeleteTenant) rather than orphan associations no API call can remove.
String assocPrefix = associationKeyPrefix(region, tenant.tenantId());
for (String assocKey : associationStore.keys().stream()
.filter(k -> k.startsWith(assocPrefix)).toList()) {
associationStore.delete(assocKey);
}
tenantStore.delete(key);
}
@@ -115,6 +150,200 @@ public class SesTenantService {
return tenantStore.get(tenantKey(region, tenantName));
}
// ──────────────────────── Resource associations (Phase 2) ────────────────────────
// Behavior and messages probe-confirmed against real AWS us-east-1, 2026-08-28.
/**
* Resolves the tenant for the association operations. Unlike the CRUD operations, the association
* request shapes carry no Smithy min-length on TenantName, so an empty value gets the
* service-level message instead of the Smithy one.
*/
public Tenant tenantForAssociation(String tenantName, String region) {
if (tenantName == null) {
throw new AwsException("BadRequestException",
"1 validation error detected: Value at 'tenantName' failed to satisfy constraint: "
+ "Member must not be null", 400);
}
if (tenantName.isBlank()) {
throw new AwsException("BadRequestException", "TenantName cannot be empty", 400);
}
return tenantStore.get(tenantKey(region, tenantName))
.orElseThrow(() -> tenantNotFound(tenantName));
}
/**
* Parses and format-validates a resource ARN for the association operations. Check order matches
* the observed AWS precedence: not an ARN at all, then not an SES ARN, then an unsupported SES
* resource type, then region and account mismatches. Existence is the facade's job.
*/
public static AssociationResource parseResourceArn(String resourceArn, String accountId, String region) {
if (resourceArn == null) {
throw new AwsException("BadRequestException",
"1 validation error detected: Value at 'resourceArn' failed to satisfy constraint: "
+ "Member must not be null", 400);
}
String[] parts = resourceArn.split(":", 6);
if (parts.length < 6 || !"arn".equals(parts[0])) {
throw new AwsException("BadRequestException",
"Provided resource identifier is not an SES resource", 400);
}
if (!"ses".equals(parts[2])) {
throw new AwsException("BadRequestException",
"Provided ARN is not in SES resource ARN format", 400);
}
String resource = parts[5];
int slash = resource.indexOf('/');
String type = slash < 0 ? resource : resource.substring(0, slash);
if (!SUPPORTED_RESOURCE_TYPES.contains(type)) {
throw new AwsException("BadRequestException", "Unsupported resource type: " + type, 400);
}
if (slash < 0 || slash == resource.length() - 1) {
// A supported type with no name segment can never reference a resource; reject it as
// malformed rather than letting it 404 with an empty name.
throw new AwsException("BadRequestException",
"Provided resource identifier is not an SES resource", 400);
}
if (!region.equals(parts[3])) {
throw new AwsException("BadRequestException",
"Resource <" + resourceArn + "> must be in the same region", 400);
}
if (!accountId.equals(parts[4])) {
throw new AwsException("BadRequestException",
"Resource <" + resourceArn + "> must be in the same account", 400);
}
return new AssociationResource(type, resource.substring(slash + 1), resourceArn);
}
/**
* Creates the association under the shared lock. The tenant is revalidated (a concurrent
* {@code DeleteTenant} may have cascaded since the caller resolved it) and
* {@code resourceExistenceCheck} — the facade's throwing existence check — runs inside the lock
* too, so a backing resource cannot slip through {@link #deleteBackingResource} concurrently and
* leave an association pointing at a deleted resource.
*/
public void associate(Tenant tenant, AssociationResource ref, String region,
Runnable resourceExistenceCheck) {
String key = associationKey(region, tenant.tenantId(), ref);
synchronized (tenantMutationLock) {
Tenant current = tenantStore.get(tenantKey(region, tenant.tenantName())).orElse(null);
if (current == null || !tenant.tenantId().equals(current.tenantId())) {
throw tenantNotFound(tenant.tenantName());
}
resourceExistenceCheck.run();
if (associationStore.get(key).isPresent()) {
// "Resources" is AWS's own grammar for this message.
throw new AwsException("AlreadyExistsException",
"Resources " + ref.arn() + " has already been associated with tenant "
+ tenant.tenantName(), 400);
}
associationStore.put(key, new TenantResourceAssociation(tenant.tenantName(),
tenant.tenantId(), ref.arn(), ref.type(), Instant.now(clock)));
}
LOG.infov("Associated SES resource {0} with tenant {1} in region {2}",
ref.arn(), tenant.tenantName(), region);
}
/**
* Runs a backing-resource deletion under the same lock as association creation: AWS refuses to
* delete an identity, configuration set, or template that still has tenant associations, and the
* shared lock keeps that guard atomic with {@link #associate}'s existence check.
*/
public void deleteBackingResource(String resourceType, String resourceName, String region,
Runnable deleteAction) {
synchronized (tenantMutationLock) {
findAssociationForResource(resourceType, resourceName, region).ifPresent(a -> {
throw new AwsException("BadRequestException",
"Cannot delete <" + a.resourceArn() + "> because it has tenant associations. "
+ "Remove all tenant associations and try again.", 400);
});
deleteAction.run();
}
}
/** Removing an association that does not exist is a silent success on AWS. */
public void disassociate(Tenant tenant, AssociationResource ref, String region) {
associationStore.delete(associationKey(region, tenant.tenantId(), ref));
LOG.infov("Disassociated SES resource {0} from tenant {1} in region {2}",
ref.arn(), tenant.tenantName(), region);
}
/** AWS returns the tenant's resources ordered by ARN. */
public List<TenantResourceAssociation> listTenantResources(Tenant tenant, String typeFilter,
String region) {
String prefix = associationKeyPrefix(region, tenant.tenantId());
return associationStore.scan(k -> k.startsWith(prefix)).stream()
.filter(a -> typeFilter == null || typeFilter.equals(a.resourceType()))
.sorted(Comparator.comparing(TenantResourceAssociation::resourceArn,
Comparator.nullsLast(Comparator.naturalOrder())))
.toList();
}
// The resource lookups match on the stored record, not on a key suffix: a resource name may
// itself contain the "::" delimiter (Floci barely restricts identity and template names), so a
// suffix match on the key could alias one resource's associations to another's.
/** AWS returns a resource's tenants ordered by association time. */
public List<TenantResourceAssociation> listResourceTenants(AssociationResource ref, String region) {
String regionPrefix = "tenantAssoc::" + region + "::";
return associationStore.scan(k -> k.startsWith(regionPrefix)).stream()
.filter(a -> ref.arn().equals(a.resourceArn()))
.sorted(Comparator.comparing(TenantResourceAssociation::associatedTimestamp,
Comparator.nullsLast(Comparator.naturalOrder()))
.thenComparing(TenantResourceAssociation::tenantName,
Comparator.nullsLast(Comparator.naturalOrder())))
.toList();
}
/**
* Finds any association for the given resource, for the facade's delete guards: AWS refuses to
* delete an identity, configuration set, or template that still has tenant associations.
*/
public Optional<TenantResourceAssociation> findAssociationForResource(String resourceType,
String resourceName,
String region) {
String regionPrefix = "tenantAssoc::" + region + "::";
return associationStore.scan(k -> k.startsWith(regionPrefix)).stream()
.filter(a -> resourceType.equals(a.resourceType())
&& resourceName.equals(resourceNameFromArn(a.resourceArn())))
.findFirst();
}
// Stored ARNs were validated by parseResourceArn, so the resource part always has a name segment.
private static String resourceNameFromArn(String arn) {
String resource = arn.split(":", 6)[5];
return resource.substring(resource.indexOf('/') + 1);
}
public static void validateResourceTypeFilter(String value) {
if (value != null && !SUPPORTED_RESOURCE_TYPES.contains(value)) {
throw new AwsException("BadRequestException",
"Invalid resource type " + value + " specified.", 400);
}
}
/**
* The list operations return everything in one page, so any client-supplied NextToken is invalid —
* which is also what AWS answers for a token it cannot decrypt. PageSize is still range-checked.
*/
public static void validateListPaging(Integer pageSize, String nextToken) {
if (pageSize != null && pageSize < 1) {
throw new AwsException("BadRequestException",
"1 validation error detected: Value '" + pageSize + "' at 'pageSize' failed to "
+ "satisfy constraint: Member must have value greater than or equal to 1", 400);
}
if (nextToken != null) {
throw new AwsException("BadRequestException", "Invalid Next Token", 400);
}
}
private static String associationKey(String region, String tenantId, AssociationResource ref) {
return associationKeyPrefix(region, tenantId) + ref.type() + "::" + ref.name();
}
private static String associationKeyPrefix(String region, String tenantId) {
return "tenantAssoc::" + region + "::" + tenantId + "::";
}
// Validation order and messages verified against real AWS (2026-08-22): an empty string is the
// Smithy min-length violation, a whitespace-only value is "cannot be empty", then length, then the
// character-set rule.
@@ -0,0 +1,18 @@
package io.github.hectorvent.floci.services.ses.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
/**
* A SES v2 tenant→resource association, created by {@code CreateTenantResourceAssociation}.
* {@code resourceType} is the wire value AWS uses for these APIs — the ARN segment
* ({@code identity} / {@code configuration-set} / {@code template}), not the SDK enum spelling.
*/
@RegisterForReflection
public record TenantResourceAssociation(String tenantName,
String tenantId,
String resourceArn,
String resourceType,
Instant associatedTimestamp) {
}
@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.ses.model.ReceiptRuleSet;
import io.github.hectorvent.floci.services.ses.model.SentEmail;
import io.github.hectorvent.floci.services.ses.model.SuppressedDestination;
import io.github.hectorvent.floci.services.ses.model.Tenant;
import io.github.hectorvent.floci.services.ses.model.TenantResourceAssociation;
import io.github.hectorvent.floci.services.route53.Route53Service;
import java.security.SecureRandom;
@@ -48,6 +49,8 @@ final class SesServiceTestBuilder {
private final InMemoryStorage<String, ReceiptRuleSet> receiptRuleStore = new InMemoryStorage<>();
private final InMemoryStorage<String, CustomVerificationEmailTemplate> cvetStore = new InMemoryStorage<>();
private final InMemoryStorage<String, Tenant> tenantStore = new InMemoryStorage<>();
private final InMemoryStorage<String, TenantResourceAssociation> tenantAssociationStore =
new InMemoryStorage<>();
private SmtpRelay smtpRelay = mock(SmtpRelay.class);
// Default null, matching the production null-Route53 case: SesService treats a null Route53Service
@@ -124,7 +127,7 @@ final class SesServiceTestBuilder {
new SesPolicyService(policyStore, objectMapper),
new SesReceiptRuleService(receiptRuleStore, clock),
new SesCvetService(cvetStore),
new SesTenantService(tenantStore, clock, new SecureRandom()),
new SesTenantService(tenantStore, tenantAssociationStore, clock, new SecureRandom()),
smtpRelay,
objectMapper,
route53Service,
@@ -0,0 +1,279 @@
package io.github.hectorvent.floci.services.ses;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.startsWith;
/**
* Integration tests for the SES v2 tenant resource associations (Phase 2): the RPC-style
* {@code /tenants/resources}, {@code /tenants/resources/delete}, {@code /tenants/resources/list} and
* {@code /resources/tenants/list}. The wire quirks are probe-confirmed against real AWS: ResourceType
* values are the ARN segments (identity / configuration-set / template) — not the SDK enum spelling —
* delete is idempotent, backing-resource deletion is blocked while associated, and DeleteTenant
* cascades.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SesTenantAssociationV2IntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request";
private static final String TENANT = "floci-assoc-tenant";
private static final String TENANT_B = "floci-assoc-tenant-b";
private static final String IDENTITY = "floci-assoc.example.com";
private static final String CONFIG_SET = "floci-assoc-cs";
private static final String TEMPLATE = "floci-assoc-tpl";
private static final String ARN_PREFIX = "arn:aws:ses:us-east-1:000000000000:";
private static final String IDENTITY_ARN = ARN_PREFIX + "identity/" + IDENTITY;
private static final String CONFIG_SET_ARN = ARN_PREFIX + "configuration-set/" + CONFIG_SET;
private static final String TEMPLATE_ARN = ARN_PREFIX + "template/" + TEMPLATE;
private static io.restassured.specification.RequestSpecification v2() {
return given().contentType("application/json").header("Authorization", AUTH);
}
private static void associate(String tenant, String arn) {
v2().body("{\"TenantName\":\"" + tenant + "\",\"ResourceArn\":\"" + arn + "\"}")
.when().post("/v2/email/tenants/resources").then().statusCode(200);
}
@Test
@Order(1)
void setup_createTenantsAndResources() {
v2().body("{\"TenantName\":\"" + TENANT + "\"}")
.when().post("/v2/email/tenants").then().statusCode(200);
v2().body("{\"TenantName\":\"" + TENANT_B + "\"}")
.when().post("/v2/email/tenants").then().statusCode(200);
v2().body("{\"EmailIdentity\":\"" + IDENTITY + "\"}")
.when().post("/v2/email/identities").then().statusCode(200);
v2().body("{\"ConfigurationSetName\":\"" + CONFIG_SET + "\"}")
.when().post("/v2/email/configuration-sets").then().statusCode(200);
v2().body("{\"TemplateName\":\"" + TEMPLATE + "\",\"TemplateContent\":{\"Subject\":\"s\",\"Text\":\"t\"}}")
.when().post("/v2/email/templates").then().statusCode(200);
}
@Test
@Order(2)
void createAssociation_returnsEmptyObject() {
v2().body("{\"TenantName\":\"" + TENANT + "\",\"ResourceArn\":\"" + IDENTITY_ARN + "\"}")
.when().post("/v2/email/tenants/resources").then().statusCode(200)
.body("isEmpty()", equalTo(true));
associate(TENANT, CONFIG_SET_ARN);
associate(TENANT, TEMPLATE_ARN);
associate(TENANT_B, IDENTITY_ARN);
}
@Test
@Order(3)
void createAssociation_duplicate_returnsAlreadyExists() {
v2().body("{\"TenantName\":\"" + TENANT + "\",\"ResourceArn\":\"" + IDENTITY_ARN + "\"}")
.when().post("/v2/email/tenants/resources").then().statusCode(400)
.body("__type", equalTo("AlreadyExistsException"))
// "Resources" is AWS's own grammar.
.body("message", equalTo("Resources " + IDENTITY_ARN
+ " has already been associated with tenant " + TENANT));
}
@Test
@Order(4)
void createAssociation_errorMatrix() {
v2().body("{\"TenantName\":\"ghost-tenant\",\"ResourceArn\":\"" + IDENTITY_ARN + "\"}")
.when().post("/v2/email/tenants/resources").then().statusCode(404)
.body("__type", equalTo("NotFoundException"))
.body("message", equalTo("The requested tenant <ghost-tenant> does not exist."));
// Missing resources 404 with a per-type message; the configuration-set trailing colon is AWS's.
v2().body("{\"TenantName\":\"" + TENANT + "\",\"ResourceArn\":\"" + ARN_PREFIX
+ "configuration-set/ghost-cs\"}")
.when().post("/v2/email/tenants/resources").then().statusCode(404)
.body("message", equalTo("Configuration set <ghost-cs> does not exist:"));
v2().body("{\"TenantName\":\"" + TENANT + "\",\"ResourceArn\":\"" + ARN_PREFIX
+ "identity/ghost.example.com\"}")
.when().post("/v2/email/tenants/resources").then().statusCode(404)
.body("message", equalTo("Identity <ghost.example.com> does not exist"));
v2().body("{\"TenantName\":\"" + TENANT + "\",\"ResourceArn\":\"" + ARN_PREFIX
+ "template/ghost-tpl\"}")
.when().post("/v2/email/tenants/resources").then().statusCode(404)
.body("message", equalTo("Email template <ghost-tpl> does not exist"));
v2().body("{\"TenantName\":\"" + TENANT + "\",\"ResourceArn\":\"not-an-arn\"}")
.when().post("/v2/email/tenants/resources").then().statusCode(400)
.body("message", equalTo("Provided resource identifier is not an SES resource"));
v2().body("{\"TenantName\":\"" + TENANT
+ "\",\"ResourceArn\":\"arn:aws:sqs:us-east-1:000000000000:q\"}")
.when().post("/v2/email/tenants/resources").then().statusCode(400)
.body("message", equalTo("Provided ARN is not in SES resource ARN format"));
v2().body("{\"TenantName\":\"" + TENANT
+ "\",\"ResourceArn\":\"arn:aws:ses:us-east-1:000000000000:contact-list/x\"}")
.when().post("/v2/email/tenants/resources").then().statusCode(400)
.body("message", equalTo("Unsupported resource type: contact-list"));
v2().body("{\"TenantName\":\"" + TENANT
+ "\",\"ResourceArn\":\"arn:aws:ses:eu-west-1:000000000000:identity/" + IDENTITY + "\"}")
.when().post("/v2/email/tenants/resources").then().statusCode(400)
.body("message", equalTo("Resource <arn:aws:ses:eu-west-1:000000000000:identity/"
+ IDENTITY + "> must be in the same region"));
v2().body("{\"TenantName\":\"" + TENANT
+ "\",\"ResourceArn\":\"arn:aws:ses:us-east-1:111111111111:identity/" + IDENTITY + "\"}")
.when().post("/v2/email/tenants/resources").then().statusCode(400)
.body("message", equalTo("Resource <arn:aws:ses:us-east-1:111111111111:identity/"
+ IDENTITY + "> must be in the same account"));
v2().body("{\"TenantName\":\"\",\"ResourceArn\":\"" + IDENTITY_ARN + "\"}")
.when().post("/v2/email/tenants/resources").then().statusCode(400)
.body("message", equalTo("TenantName cannot be empty"));
v2().body("{\"TenantName\":\"" + TENANT + "\"}")
.when().post("/v2/email/tenants/resources").then().statusCode(400)
.body("message", equalTo("1 validation error detected: Value at 'resourceArn' failed "
+ "to satisfy constraint: Member must not be null"));
}
@Test
@Order(5)
void listTenantResources_sortedByArn_lowercaseTypes_nullNextToken() {
v2().body("{\"TenantName\":\"" + TENANT + "\"}")
.when().post("/v2/email/tenants/resources/list").then().statusCode(200)
.body("NextToken", nullValue())
.body("TenantResources", hasSize(3))
.body("TenantResources[0].ResourceType", equalTo("configuration-set"))
.body("TenantResources[0].ResourceArn", equalTo(CONFIG_SET_ARN))
.body("TenantResources[1].ResourceType", equalTo("identity"))
.body("TenantResources[2].ResourceType", equalTo("template"));
}
@Test
@Order(6)
void listTenantResources_filterUsesWireValues() {
v2().body("{\"TenantName\":\"" + TENANT + "\",\"Filter\":{\"RESOURCE_TYPE\":\"identity\"}}")
.when().post("/v2/email/tenants/resources/list").then().statusCode(200)
.body("TenantResources", hasSize(1))
.body("TenantResources[0].ResourceArn", equalTo(IDENTITY_ARN));
// Real AWS rejects the SDK's enum spelling — only the ARN-segment values are valid.
v2().body("{\"TenantName\":\"" + TENANT + "\",\"Filter\":{\"RESOURCE_TYPE\":\"EMAIL_IDENTITY\"}}")
.when().post("/v2/email/tenants/resources/list").then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("Invalid resource type EMAIL_IDENTITY specified."));
}
@Test
@Order(7)
void listTenantResources_pagingValidation() {
v2().body("{\"TenantName\":\"" + TENANT + "\",\"PageSize\":0}")
.when().post("/v2/email/tenants/resources/list").then().statusCode(400)
.body("message", equalTo("1 validation error detected: Value '0' at 'pageSize' failed "
+ "to satisfy constraint: Member must have value greater than or equal to 1"));
v2().body("{\"TenantName\":\"" + TENANT + "\",\"NextToken\":\"garbage-token\"}")
.when().post("/v2/email/tenants/resources/list").then().statusCode(400)
.body("message", equalTo("Invalid Next Token"));
// An integral value outside the int range must be rejected, not silently truncated
// (4294967296 would truncate to 0 and produce the wrong Smithy message).
v2().body("{\"TenantName\":\"" + TENANT + "\",\"PageSize\":4294967296}")
.when().post("/v2/email/tenants/resources/list").then().statusCode(400)
.body("__type", equalTo("SerializationException"));
v2().body("{\"TenantName\":\"ghost-tenant\"}")
.when().post("/v2/email/tenants/resources/list").then().statusCode(404)
.body("__type", equalTo("NotFoundException"));
}
@Test
@Order(8)
void listResourceTenants_returnsMetadataWithoutTenantArn() {
v2().body("{\"ResourceArn\":\"" + IDENTITY_ARN + "\"}")
.when().post("/v2/email/resources/tenants/list").then().statusCode(200)
.body("NextToken", nullValue())
.body("ResourceTenants", hasSize(2))
.body("ResourceTenants[0].TenantName", equalTo(TENANT))
.body("ResourceTenants[0].TenantId", startsWith("tn-"))
.body("ResourceTenants[0].ResourceArn", equalTo(IDENTITY_ARN))
.body("ResourceTenants[0].AssociatedTimestamp", notNullValue())
.body("ResourceTenants[0].TenantArn", nullValue())
.body("ResourceTenants[1].TenantName", equalTo(TENANT_B));
v2().body("{\"ResourceArn\":\"" + ARN_PREFIX + "configuration-set/ghost-cs\"}")
.when().post("/v2/email/resources/tenants/list").then().statusCode(404)
.body("message", equalTo("Configuration set <ghost-cs> does not exist:"));
v2().body("{\"ResourceArn\":\"nope\"}")
.when().post("/v2/email/resources/tenants/list").then().statusCode(400)
.body("message", equalTo("Provided resource identifier is not an SES resource"));
}
@Test
@Order(9)
void deleteBackingResource_whileAssociated_isBlocked() {
v2().when().delete("/v2/email/identities/" + IDENTITY).then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("Cannot delete <" + IDENTITY_ARN + "> because it has tenant "
+ "associations. Remove all tenant associations and try again."));
v2().when().delete("/v2/email/configuration-sets/" + CONFIG_SET).then().statusCode(400)
.body("message", equalTo("Cannot delete <" + CONFIG_SET_ARN + "> because it has tenant "
+ "associations. Remove all tenant associations and try again."));
v2().when().delete("/v2/email/templates/" + TEMPLATE).then().statusCode(400)
.body("message", equalTo("Cannot delete <" + TEMPLATE_ARN + "> because it has tenant "
+ "associations. Remove all tenant associations and try again."));
}
@Test
@Order(10)
void deleteAssociation_isIdempotent_butValidatesTenantAndResource() {
v2().body("{\"TenantName\":\"" + TENANT + "\",\"ResourceArn\":\"" + TEMPLATE_ARN + "\"}")
.when().post("/v2/email/tenants/resources/delete").then().statusCode(200)
.body("isEmpty()", equalTo(true));
// Removing an association that no longer exists is a silent success on AWS.
v2().body("{\"TenantName\":\"" + TENANT + "\",\"ResourceArn\":\"" + TEMPLATE_ARN + "\"}")
.when().post("/v2/email/tenants/resources/delete").then().statusCode(200);
v2().body("{\"TenantName\":\"ghost-tenant\",\"ResourceArn\":\"" + IDENTITY_ARN + "\"}")
.when().post("/v2/email/tenants/resources/delete").then().statusCode(404)
.body("__type", equalTo("NotFoundException"));
v2().body("{\"TenantName\":\"" + TENANT + "\",\"ResourceArn\":\"" + ARN_PREFIX
+ "configuration-set/ghost-cs\"}")
.when().post("/v2/email/tenants/resources/delete").then().statusCode(404)
.body("message", equalTo("Configuration set <ghost-cs> does not exist:"));
}
@Test
@Order(11)
void deleteTenant_cascadesAssociations_andRecreationStartsClean() {
v2().body("{\"TenantName\":\"" + TENANT + "\"}")
.when().post("/v2/email/tenants/delete").then().statusCode(200);
// Only TENANT_B's association survives the cascade.
v2().body("{\"ResourceArn\":\"" + IDENTITY_ARN + "\"}")
.when().post("/v2/email/resources/tenants/list").then().statusCode(200)
.body("ResourceTenants", hasSize(1))
.body("ResourceTenants[0].TenantName", equalTo(TENANT_B));
v2().body("{\"ResourceArn\":\"" + CONFIG_SET_ARN + "\"}")
.when().post("/v2/email/resources/tenants/list").then().statusCode(200)
.body("ResourceTenants", hasSize(0));
// A recreated same-name tenant has a new TenantId and sees none of the old associations.
v2().body("{\"TenantName\":\"" + TENANT + "\"}")
.when().post("/v2/email/tenants").then().statusCode(200);
v2().body("{\"TenantName\":\"" + TENANT + "\"}")
.when().post("/v2/email/tenants/resources/list").then().statusCode(200)
.body("TenantResources", hasSize(0));
v2().body("{\"TenantName\":\"" + TENANT + "\"}")
.when().post("/v2/email/tenants/delete").then().statusCode(200);
}
@Test
@Order(12)
void cleanup_afterDisassociation_backingResourcesDeletable() {
v2().body("{\"TenantName\":\"" + TENANT_B + "\",\"ResourceArn\":\"" + IDENTITY_ARN + "\"}")
.when().post("/v2/email/tenants/resources/delete").then().statusCode(200);
v2().body("{\"TenantName\":\"" + TENANT_B + "\"}")
.when().post("/v2/email/tenants/delete").then().statusCode(200);
v2().when().delete("/v2/email/identities/" + IDENTITY).then().statusCode(200);
v2().when().delete("/v2/email/configuration-sets/" + CONFIG_SET).then().statusCode(200);
v2().when().delete("/v2/email/templates/" + TEMPLATE).then().statusCode(200);
}
}
@@ -16,8 +16,10 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Unit test for the tenant domain (Phase 1 CRUD): create/get/list/delete, id/ARN generation, and the
* probe-confirmed name validation and duplicate/not-found errors. Constructed with just its own store.
* Unit test for the tenant domain: the Phase 1 CRUD (create/get/list/delete, id/ARN generation, name
* validation) and the Phase 2 resource associations (ARN parsing, duplicate/idempotency semantics,
* sorting, cascade on tenant delete). Constructed with just its own stores; resource existence is the
* facade's concern and is covered by the integration tests.
*/
class SesTenantServiceTest {
@@ -27,7 +29,8 @@ class SesTenantServiceTest {
@BeforeEach
void setUp() {
service = new SesTenantService(new InMemoryStorage<>(), Clock.systemUTC(), new SecureRandom());
service = new SesTenantService(new InMemoryStorage<>(), new InMemoryStorage<>(),
Clock.systemUTC(), new SecureRandom());
}
@Test
@@ -130,4 +133,199 @@ class SesTenantServiceTest {
AwsException d = assertThrows(AwsException.class, () -> service.deleteTenant(" ", REGION));
assertEquals("BadRequestException", d.getErrorCode());
}
// ──────────────────────── Resource associations (Phase 2) ────────────────────────
private static SesTenantService.AssociationResource identityRef(String name) {
return SesTenantService.parseResourceArn(
"arn:aws:ses:" + REGION + ":" + ACCOUNT + ":identity/" + name, ACCOUNT, REGION);
}
@Test
void parseResourceArn_acceptsThreeTypes_andExtractsName() {
SesTenantService.AssociationResource ref = SesTenantService.parseResourceArn(
"arn:aws:ses:" + REGION + ":" + ACCOUNT + ":configuration-set/my-cs", ACCOUNT, REGION);
assertEquals("configuration-set", ref.type());
assertEquals("my-cs", ref.name());
}
@Test
void parseResourceArn_errorChainMatchesAws() {
assertEquals("Provided resource identifier is not an SES resource",
assertThrows(AwsException.class,
() -> SesTenantService.parseResourceArn("not-an-arn", ACCOUNT, REGION)).getMessage());
assertEquals("Provided ARN is not in SES resource ARN format",
assertThrows(AwsException.class, () -> SesTenantService.parseResourceArn(
"arn:aws:sqs:" + REGION + ":" + ACCOUNT + ":q", ACCOUNT, REGION)).getMessage());
assertEquals("Unsupported resource type: contact-list",
assertThrows(AwsException.class, () -> SesTenantService.parseResourceArn(
"arn:aws:ses:" + REGION + ":" + ACCOUNT + ":contact-list/x", ACCOUNT, REGION)).getMessage());
assertTrue(assertThrows(AwsException.class, () -> SesTenantService.parseResourceArn(
"arn:aws:ses:eu-west-1:" + ACCOUNT + ":identity/a", ACCOUNT, REGION))
.getMessage().endsWith("must be in the same region"));
assertTrue(assertThrows(AwsException.class, () -> SesTenantService.parseResourceArn(
"arn:aws:ses:" + REGION + ":111111111111:identity/a", ACCOUNT, REGION))
.getMessage().endsWith("must be in the same account"));
assertTrue(assertThrows(AwsException.class,
() -> SesTenantService.parseResourceArn(null, ACCOUNT, REGION))
.getMessage().contains("'resourceArn'"));
}
@Test
void parseResourceArn_rejectsMissingOrEmptyName() {
// A supported type without a name segment must be rejected as malformed, not resolved to an
// empty-name resource that would 404 with a misleading message.
assertEquals("Provided resource identifier is not an SES resource",
assertThrows(AwsException.class, () -> SesTenantService.parseResourceArn(
"arn:aws:ses:" + REGION + ":" + ACCOUNT + ":identity", ACCOUNT, REGION)).getMessage());
assertEquals("Provided resource identifier is not an SES resource",
assertThrows(AwsException.class, () -> SesTenantService.parseResourceArn(
"arn:aws:ses:" + REGION + ":" + ACCOUNT + ":identity/", ACCOUNT, REGION)).getMessage());
}
@Test
void resourceLookups_dontAliasNamesContainingDelimiter() {
// Floci barely restricts resource names, so "x" and "template::x" can both exist; the
// lookups must not let a key-suffix match blur them together.
Tenant tenant = service.createTenant("acme", List.of(), ACCOUNT, REGION);
SesTenantService.AssociationResource plain = SesTenantService.parseResourceArn(
"arn:aws:ses:" + REGION + ":" + ACCOUNT + ":template/x", ACCOUNT, REGION);
SesTenantService.AssociationResource tricky = SesTenantService.parseResourceArn(
"arn:aws:ses:" + REGION + ":" + ACCOUNT + ":template/template::x", ACCOUNT, REGION);
service.associate(tenant, tricky, REGION, () -> {});
assertEquals(0, service.listResourceTenants(plain, REGION).size());
assertTrue(service.findAssociationForResource("template", "x", REGION).isEmpty());
assertEquals(1, service.listResourceTenants(tricky, REGION).size());
assertTrue(service.findAssociationForResource("template", "template::x", REGION).isPresent());
}
@Test
void associate_duplicateThrows_awsGrammarPreserved() {
Tenant tenant = service.createTenant("acme", List.of(), ACCOUNT, REGION);
SesTenantService.AssociationResource ref = identityRef("example.com");
service.associate(tenant, ref, REGION, () -> {});
AwsException e = assertThrows(AwsException.class,
() -> service.associate(tenant, ref, REGION, () -> {}));
assertEquals("AlreadyExistsException", e.getErrorCode());
assertEquals("Resources " + ref.arn() + " has already been associated with tenant acme",
e.getMessage());
}
@Test
void disassociate_isIdempotent() {
Tenant tenant = service.createTenant("acme", List.of(), ACCOUNT, REGION);
service.disassociate(tenant, identityRef("example.com"), REGION);
service.associate(tenant, identityRef("example.com"), REGION, () -> {});
service.disassociate(tenant, identityRef("example.com"), REGION);
assertEquals(0, service.listTenantResources(tenant, null, REGION).size());
}
@Test
void listTenantResources_sortedByArn_andFilterable() {
Tenant tenant = service.createTenant("acme", List.of(), ACCOUNT, REGION);
service.associate(tenant, identityRef("example.com"), REGION, () -> {});
service.associate(tenant, SesTenantService.parseResourceArn(
"arn:aws:ses:" + REGION + ":" + ACCOUNT + ":template/tpl", ACCOUNT, REGION),
REGION, () -> {});
service.associate(tenant, SesTenantService.parseResourceArn(
"arn:aws:ses:" + REGION + ":" + ACCOUNT + ":configuration-set/cs", ACCOUNT, REGION),
REGION, () -> {});
var all = service.listTenantResources(tenant, null, REGION);
assertEquals(List.of("configuration-set", "identity", "template"),
all.stream().map(a -> a.resourceType()).toList());
var filtered = service.listTenantResources(tenant, "identity", REGION);
assertEquals(1, filtered.size());
assertEquals("identity", filtered.get(0).resourceType());
}
@Test
void listResourceTenants_findsAllTenants_ofOneResource() {
Tenant a = service.createTenant("acme", List.of(), ACCOUNT, REGION);
Tenant b = service.createTenant("beta", List.of(), ACCOUNT, REGION);
service.associate(a, identityRef("example.com"), REGION, () -> {});
service.associate(b, identityRef("example.com"), REGION, () -> {});
var tenants = service.listResourceTenants(identityRef("example.com"), REGION);
assertEquals(2, tenants.size());
assertEquals("acme", tenants.get(0).tenantName());
assertEquals(a.tenantId(), tenants.get(0).tenantId());
}
@Test
void deleteTenant_cascadesAssociations_recreatedTenantSeesNone() {
Tenant tenant = service.createTenant("acme", List.of(), ACCOUNT, REGION);
service.associate(tenant, identityRef("example.com"), REGION, () -> {});
service.deleteTenant("acme", REGION);
assertEquals(0, service.listResourceTenants(identityRef("example.com"), REGION).size());
Tenant recreated = service.createTenant("acme", List.of(), ACCOUNT, REGION);
assertEquals(0, service.listTenantResources(recreated, null, REGION).size());
}
@Test
void associate_staleTenant_throwsNotFound() {
// A tenant resolved before a concurrent DeleteTenant (same or recreated name) must not be
// able to insert an orphan association: associate revalidates the TenantId under the lock.
Tenant stale = service.createTenant("acme", List.of(), ACCOUNT, REGION);
service.deleteTenant("acme", REGION);
AwsException gone = assertThrows(AwsException.class,
() -> service.associate(stale, identityRef("example.com"), REGION, () -> {}));
assertEquals("NotFoundException", gone.getErrorCode());
service.createTenant("acme", List.of(), ACCOUNT, REGION);
AwsException recreated = assertThrows(AwsException.class,
() -> service.associate(stale, identityRef("example.com"), REGION, () -> {}));
assertEquals("NotFoundException", recreated.getErrorCode());
}
@Test
void deleteBackingResource_blocksWhileAssociated_runsActionOtherwise() {
Tenant tenant = service.createTenant("acme", List.of(), ACCOUNT, REGION);
service.associate(tenant, identityRef("example.com"), REGION, () -> {});
AwsException blocked = assertThrows(AwsException.class, () -> service.deleteBackingResource(
"identity", "example.com", REGION, () -> {}));
assertEquals("Cannot delete <" + identityRef("example.com").arn() + "> because it has tenant "
+ "associations. Remove all tenant associations and try again.", blocked.getMessage());
boolean[] ran = {false};
service.deleteBackingResource("identity", "other.com", REGION, () -> ran[0] = true);
assertTrue(ran[0]);
}
@Test
void findAssociationForResource_backsDeleteGuards() {
Tenant tenant = service.createTenant("acme", List.of(), ACCOUNT, REGION);
service.associate(tenant, identityRef("example.com"), REGION, () -> {});
assertTrue(service.findAssociationForResource("identity", "example.com", REGION).isPresent());
assertTrue(service.findAssociationForResource("identity", "other.com", REGION).isEmpty());
assertTrue(service.findAssociationForResource("identity", "example.com", "eu-west-1").isEmpty());
}
@Test
void tenantForAssociation_hasServiceLevelEmptyMessage() {
AwsException empty = assertThrows(AwsException.class,
() -> service.tenantForAssociation("", REGION));
assertEquals("TenantName cannot be empty", empty.getMessage());
AwsException absent = assertThrows(AwsException.class,
() -> service.tenantForAssociation(null, REGION));
assertTrue(absent.getMessage().contains("'tenantName'"));
AwsException missing = assertThrows(AwsException.class,
() -> service.tenantForAssociation("ghost", REGION));
assertEquals("NotFoundException", missing.getErrorCode());
}
@Test
void validateFilterAndPaging_matchAwsMessages() {
assertEquals("Invalid resource type NOPE specified.",
assertThrows(AwsException.class,
() -> SesTenantService.validateResourceTypeFilter("NOPE")).getMessage());
assertEquals("Invalid resource type EMAIL_IDENTITY specified.",
assertThrows(AwsException.class,
() -> SesTenantService.validateResourceTypeFilter("EMAIL_IDENTITY")).getMessage());
assertTrue(assertThrows(AwsException.class,
() -> SesTenantService.validateListPaging(0, null))
.getMessage().contains("greater than or equal to 1"));
assertEquals("Invalid Next Token",
assertThrows(AwsException.class,
() -> SesTenantService.validateListPaging(null, "garbage")).getMessage());
}
}