feat(ses): support v2 tenant CRUD (CreateTenant/GetTenant/ListTenants/DeleteTenant) (#2644)

* feat(ses): support v2 tenant CRUD (CreateTenant/GetTenant/ListTenants/DeleteTenant)

Add the first phase of SES v2 multi-tenancy: tenant create/get/list/delete via the
RPC-style POST routes under /v2/email/tenants. A new SesTenantService owns the tenant
store, id/ARN generation (tn-<hex>, arn:aws:ses:<region>:<account>:tenant/<name>/<id>),
the ENABLED sending status, and the TenantName validation (1-64 chars [A-Za-z0-9_-],
duplicate -> AlreadyExistsException, unknown -> NotFoundException); the facade delegates
and the controller only parses/renders. Resource associations, tenant suppression, and
tenant-scoped sending are follow-ups.

* docs(ses): correct account-scoping description in SesTenantService Javadoc
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-08-28 11:03:12 -04:00
1 parent c90c5adfcb
commit 2963601f69
9 files changed
+765 -2

No files matched your search

@@ -0,0 +1,123 @@
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.AlreadyExistsException;
import software.amazon.awssdk.services.sesv2.model.BadRequestException;
import software.amazon.awssdk.services.sesv2.model.CreateTenantRequest;
import software.amazon.awssdk.services.sesv2.model.CreateTenantResponse;
import software.amazon.awssdk.services.sesv2.model.DeleteTenantRequest;
import software.amazon.awssdk.services.sesv2.model.GetTenantRequest;
import software.amazon.awssdk.services.sesv2.model.GetTenantResponse;
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 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.
*/
@DisplayName("SES v2 Tenants")
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SesTenantTest {
private static final String TENANT = "compat-tenant-alpha";
private static SesV2Client sesV2;
@BeforeAll
static void setup() {
sesV2 = TestFixtures.sesV2Client();
}
@AfterAll
static void cleanup() {
if (sesV2 != null) {
try {
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();
}
}
}
@Test
@Order(1)
void createTenant_returnsGeneratedIdArnAndEnabledStatus() {
CreateTenantResponse resp = sesV2.createTenant(CreateTenantRequest.builder()
.tenantName(TENANT)
.tags(Tag.builder().key("team").value("floci").build())
.build());
assertThat(resp.tenantName()).isEqualTo(TENANT);
assertThat(resp.tenantId()).startsWith("tn-");
assertThat(resp.tenantArn()).contains(":tenant/" + TENANT + "/");
assertThat(resp.sendingStatusAsString()).isEqualTo("ENABLED");
assertThat(resp.createdTimestamp()).isNotNull();
assertThat(resp.tags()).extracting(Tag::key).contains("team");
}
@Test
@Order(2)
void getTenant_returnsTenant() {
GetTenantResponse resp = sesV2.getTenant(GetTenantRequest.builder().tenantName(TENANT).build());
assertThat(resp.tenant()).isNotNull();
assertThat(resp.tenant().tenantName()).isEqualTo(TENANT);
assertThat(resp.tenant().tenantId()).startsWith("tn-");
assertThat(resp.tenant().sendingStatusAsString()).isEqualTo("ENABLED");
}
@Test
@Order(3)
void listTenants_includesCreatedTenant() {
ListTenantsResponse resp = sesV2.listTenants(ListTenantsRequest.builder().build());
assertThat(resp.tenants()).anyMatch(t -> TENANT.equals(t.tenantName()));
}
@Test
@Order(4)
void createTenant_duplicate_throwsAlreadyExists() {
assertThatThrownBy(() -> sesV2.createTenant(CreateTenantRequest.builder()
.tenantName(TENANT).build()))
.isInstanceOf(AlreadyExistsException.class);
}
@Test
@Order(5)
void createTenant_invalidName_throwsBadRequest() {
assertThatThrownBy(() -> sesV2.createTenant(CreateTenantRequest.builder()
.tenantName("bad name!").build()))
.isInstanceOf(BadRequestException.class);
}
@Test
@Order(6)
void deleteTenant_removesIt_thenGetIsNotFound() {
sesV2.deleteTenant(DeleteTenantRequest.builder().tenantName(TENANT).build());
assertThatThrownBy(() -> sesV2.getTenant(GetTenantRequest.builder().tenantName(TENANT).build()))
.isInstanceOf(NotFoundException.class);
}
@Test
@Order(7)
void deleteTenant_missing_throwsNotFound() {
assertThatThrownBy(() -> sesV2.deleteTenant(DeleteTenantRequest.builder()
.tenantName("compat-tenant-does-not-exist").build()))
.isInstanceOf(NotFoundException.class);
}
}
+6
View File
@@ -210,6 +210,10 @@ Alongside the classic Query API, Floci implements a subset of the SES v2 REST JS
| `PUT` | `/v2/email/account/suppression` | `PutAccountSuppressionAttributes` |
| `PUT` | `/v2/email/account/vdm` | `PutAccountVdmAttributes` |
| `POST` | `/v2/email/account/details` | `PutAccountDetails` |
| `POST` | `/v2/email/tenants` | `CreateTenant` |
| `POST` | `/v2/email/tenants/get` | `GetTenant` |
| `POST` | `/v2/email/tenants/list` | `ListTenants` |
| `POST` | `/v2/email/tenants/delete` | `DeleteTenant` |
| `POST` | `/v2/email/templates` | `CreateEmailTemplate` |
| `GET` | `/v2/email/templates` | `ListEmailTemplates` |
| `GET` | `/v2/email/templates/{templateName}` | `GetEmailTemplate` |
@@ -280,6 +284,8 @@ 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.
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.
@@ -26,6 +26,7 @@ import io.github.hectorvent.floci.services.ses.model.MessageTag;
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.TrackingOptions;
import io.github.hectorvent.floci.services.ses.model.VdmOptions;
import com.fasterxml.jackson.databind.JsonNode;
@@ -849,6 +850,134 @@ public class SesController {
return o;
}
// ──────────────────────────── Tenants (multi-tenancy) ────────────────────────────
// The SES v2 tenant operations use RPC-style POST subpaths (/tenants, /tenants/get, /tenants/list,
// /tenants/delete). The service owns id/ARN generation and name validation; the controller only
// parses the request and renders the response.
@POST
@Path("/tenants")
public Response createTenant(@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");
List<Tag> tags = parseTagsArray(request.path("Tags"));
String accountId = regionResolver.getAccountId();
Tenant tenant = sesService.createTenant(tenantName, tags, accountId, region);
return Response.ok(tenantJson(tenant)).build();
} catch (AwsException e) {
throw remapV1Exception(e);
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
throw new AwsException("SerializationException", null, 400);
}
}
@POST
@Path("/tenants/get")
public Response getTenant(@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");
Tenant tenant = sesService.getTenant(tenantName, region);
ObjectNode result = objectMapper.createObjectNode();
result.set("Tenant", tenantJson(tenant));
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("/tenants/list")
public Response listTenants(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
// Parse the body so a malformed request is rejected rather than silently accepted. Phase 1
// returns every tenant in one page; PageSize/NextToken pagination is a follow-up.
JsonNode request = (body == null || body.isBlank())
? objectMapper.createObjectNode()
: objectMapper.readTree(body);
requireJsonObject(request);
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
throw new AwsException("SerializationException", null, 400);
}
ObjectNode result = objectMapper.createObjectNode();
ArrayNode tenants = result.putArray("Tenants");
for (Tenant t : sesService.listTenants(region)) {
// ListTenants returns the TenantInfo subset (no Tags / SendingStatus).
ObjectNode item = tenants.addObject();
item.put("TenantName", t.tenantName());
item.put("TenantId", t.tenantId());
item.put("TenantArn", t.tenantArn());
if (t.createdTimestamp() != null) {
item.put("CreatedTimestamp", t.createdTimestamp().toEpochMilli() / 1000.0);
}
}
return Response.ok(result).build();
}
@POST
@Path("/tenants/delete")
public Response deleteTenant(@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");
sesService.deleteTenant(tenantName, 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);
}
}
// 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) {
JsonNode n = parent.path(field);
if (n.isMissingNode() || n.isNull()) {
return null;
}
if (!n.isTextual()) {
throw new AwsException("SerializationException", null, 400);
}
return n.textValue();
}
private ObjectNode tenantJson(Tenant tenant) {
ObjectNode node = objectMapper.createObjectNode();
node.put("TenantName", tenant.tenantName());
node.put("TenantId", tenant.tenantId());
node.put("TenantArn", tenant.tenantArn());
if (tenant.createdTimestamp() != null) {
node.put("CreatedTimestamp", tenant.createdTimestamp().toEpochMilli() / 1000.0);
}
if (tenant.tags() != null && !tenant.tags().isEmpty()) {
ArrayNode tags = node.putArray("Tags");
for (Tag t : tenant.tags()) {
ObjectNode tagNode = tags.addObject();
tagNode.put("Key", t.key());
tagNode.put("Value", t.value());
}
}
node.put("SendingStatus", tenant.sendingStatus());
return node;
}
@POST
@Path("/templates")
public Response createEmailTemplate(@Context HttpHeaders headers, String body) {
@@ -35,6 +35,7 @@ import io.github.hectorvent.floci.services.ses.model.TopicPreference;
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.SuppressedDestination;
import io.github.hectorvent.floci.services.ses.model.SuppressionOptions;
import io.github.hectorvent.floci.services.ses.model.Tag;
@@ -111,6 +112,8 @@ public class SesService {
// Custom verification email templates: storage extracted to SesCvetService. The
// facade keeps the identity-dependent validation and the send path; the service owns the store.
private final SesCvetService cvetService;
// Tenants (multi-tenancy) live in SesTenantService. The facade delegates.
private final SesTenantService tenantService;
private final SmtpRelay smtpRelay;
private final ObjectMapper objectMapper;
private final SesEventPublisher eventPublisher;
@@ -131,7 +134,7 @@ public class SesService {
SesPolicyService policyService, SesContactService contactService,
SesSuppressionService suppressionService, SesDedicatedIpService dedicatedIpService,
SesTemplateService templateService, SesSentEmailService sentEmailService,
SmtpRelay smtpRelay, ObjectMapper objectMapper,
SesTenantService tenantService, SmtpRelay smtpRelay, ObjectMapper objectMapper,
SesEventPublisher eventPublisher, EmulatorConfig config, Route53Service route53Service,
RegionResolver regionResolver, Clock clock) {
this.identityStore = storageFactory.create("ses", "ses-identities.json",
@@ -147,6 +150,7 @@ public class SesService {
this.policyService = policyService;
this.receiptRuleService = receiptRuleService;
this.cvetService = cvetService;
this.tenantService = tenantService;
this.smtpRelay = smtpRelay;
this.objectMapper = objectMapper;
this.eventPublisher = eventPublisher;
@@ -168,12 +172,13 @@ public class SesService {
SesPolicyService policyService,
SesReceiptRuleService receiptRuleService,
SesCvetService cvetService,
SesTenantService tenantService,
SmtpRelay smtpRelay,
ObjectMapper objectMapper,
Clock clock) {
this(identityStore, sentEmailService, accountService, templateService, configSetStore, suppressionService,
dedicatedIpService, contactService, policyService,
receiptRuleService, cvetService, smtpRelay, objectMapper, null, clock);
receiptRuleService, cvetService, tenantService, smtpRelay, objectMapper, null, clock);
}
SesService(StorageBackend<String, Identity> identityStore,
@@ -187,6 +192,7 @@ public class SesService {
SesPolicyService policyService,
SesReceiptRuleService receiptRuleService,
SesCvetService cvetService,
SesTenantService tenantService,
SmtpRelay smtpRelay,
ObjectMapper objectMapper,
Route53Service route53Service,
@@ -202,6 +208,7 @@ public class SesService {
this.policyService = policyService;
this.receiptRuleService = receiptRuleService;
this.cvetService = cvetService;
this.tenantService = tenantService;
this.smtpRelay = smtpRelay;
this.objectMapper = objectMapper;
this.eventPublisher = null;
@@ -1638,6 +1645,25 @@ public class SesService {
return "configSet::" + region + "::" + name;
}
// ──────────────────────── Tenants (multi-tenancy) ────────────────────────
// Tenants live in SesTenantService; the facade forwards.
public Tenant createTenant(String tenantName, List<Tag> tags, String accountId, String region) {
return tenantService.createTenant(tenantName, tags, accountId, region);
}
public Tenant getTenant(String tenantName, String region) {
return tenantService.getTenant(tenantName, region);
}
public List<Tenant> listTenants(String region) {
return tenantService.listTenants(region);
}
public void deleteTenant(String tenantName, String region) {
tenantService.deleteTenant(tenantName, region);
}
// ──────────────────────── Receipt rule sets (inbound) ────────────────────────
//
// Receipt rule sets live in SesReceiptRuleService; this facade
@@ -0,0 +1,171 @@
package io.github.hectorvent.floci.services.ses;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsException;
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 jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Instant;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;
/**
* SES v2 tenants (multi-tenancy), owning the {@code tenantStore}. The domain owns id/ARN generation,
* the synthetic sending status, and the name validation so they can't be bypassed; the controller
* only parses the REST JSON. Reached through the {@code SesService} facade, which delegates here.
*
* <p>Account isolation comes from the account-aware store returned by {@code StorageFactory}: keys
* 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.
*/
@ApplicationScoped
public class SesTenantService {
private static final Logger LOG = Logger.getLogger(SesTenantService.class);
private static final int TENANT_NAME_MAX = 64;
private static final Pattern TENANT_NAME_CHARS = Pattern.compile("[A-Za-z0-9_-]+");
private static final char[] HEX = "0123456789abcdef".toCharArray();
private final StorageBackend<String, Tenant> tenantStore;
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
// succeed (InMemoryStorage only makes each individual operation thread-safe).
private final Object tenantMutationLock = new Object();
@Inject
public SesTenantService(StorageFactory storageFactory, Clock clock) {
this(storageFactory.create("ses", "ses-tenants.json",
new TypeReference<Map<String, Tenant>>() {}), clock, new SecureRandom());
}
SesTenantService(StorageBackend<String, Tenant> tenantStore, Clock clock, SecureRandom random) {
this.tenantStore = tenantStore;
this.clock = clock;
this.random = random;
}
public Tenant createTenant(String tenantName, List<Tag> tags, String accountId, String region) {
validateTenantName(tenantName);
SesTags.validate(tags);
String key = tenantKey(region, tenantName);
String tenantId = generateTenantId();
String tenantArn = "arn:aws:ses:" + region + ":" + accountId + ":tenant/" + tenantName + "/" + tenantId;
Tenant tenant = new Tenant(tenantName, tenantId, tenantArn, Instant.now(clock), tags, "ENABLED");
// 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) {
if (tenantStore.get(key).isPresent()) {
throw new AwsException("AlreadyExistsException",
"Tenant with name " + tenantName + " already exists in account " + accountId, 400);
}
tenantStore.put(key, tenant);
}
LOG.infov("Created SES tenant {0} ({1}) in account {2} region {3}",
tenantName, tenantId, accountId, region);
return tenant;
}
public Tenant getTenant(String tenantName, String region) {
// TenantName is a required, min-length-1 member, so a malformed name is a BadRequest, not a
// lookup miss.
validateTenantName(tenantName);
return tenantStore.get(tenantKey(region, tenantName))
.orElseThrow(() -> tenantNotFound(tenantName));
}
public List<Tenant> listTenants(String region) {
String prefix = tenantKeyPrefix(region);
return tenantStore.scan(k -> k.startsWith(prefix)).stream()
.sorted(Comparator.comparing(Tenant::createdTimestamp,
Comparator.nullsLast(Comparator.naturalOrder()))
.thenComparing(Tenant::tenantName, Comparator.nullsLast(Comparator.naturalOrder())))
.toList();
}
public void deleteTenant(String tenantName, String region) {
validateTenantName(tenantName);
String key = tenantKey(region, tenantName);
synchronized (tenantMutationLock) {
if (tenantStore.get(key).isEmpty()) {
throw tenantNotFound(tenantName);
}
tenantStore.delete(key);
}
LOG.infov("Deleted SES tenant {0} in region {1}", tenantName, region);
}
/** Reads a tenant without throwing, so later phases (associations, tenant-scoped send) can check
* existence through the facade without duplicating the key derivation. */
public Optional<Tenant> find(String tenantName, String region) {
return tenantStore.get(tenantKey(region, tenantName));
}
// 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.
private static void validateTenantName(String name) {
if (name == null) {
throw new AwsException("BadRequestException",
"1 validation error detected: Value at 'tenantName' failed to satisfy constraint: "
+ "Member must not be null", 400);
}
if (name.isEmpty()) {
throw new AwsException("BadRequestException",
"1 validation error detected: Value at 'tenantName' failed to satisfy constraint: "
+ "Member must have length greater than or equal to 1", 400);
}
if (name.isBlank()) {
throw new AwsException("BadRequestException", "TenantName cannot be empty", 400);
}
if (name.length() > TENANT_NAME_MAX) {
throw new AwsException("BadRequestException",
"TenantName cannot exceed " + TENANT_NAME_MAX + " characters.", 400);
}
if (!TENANT_NAME_CHARS.matcher(name).matches()) {
throw new AwsException("BadRequestException",
"Invalid tenant name <" + name + ">: only alphanumeric ASCII characters, '_', and "
+ "'-' are allowed.", 400);
}
}
private static AwsException tenantNotFound(String tenantName) {
return new AwsException("NotFoundException",
"The requested tenant <" + tenantName + "> does not exist.", 404);
}
private String generateTenantId() {
// AWS tenant ids look like "tn-" followed by 30 lowercase hex characters.
byte[] bytes = new byte[15];
random.nextBytes(bytes);
StringBuilder sb = new StringBuilder("tn-");
for (byte b : bytes) {
sb.append(HEX[(b >> 4) & 0xF]).append(HEX[b & 0xF]);
}
return sb.toString();
}
// The store is account-scoped transparently by AccountAwareStorageBackend (StorageFactory wraps
// every store), so the key only needs region + name — the same convention as the other SES stores.
private static String tenantKey(String region, String tenantName) {
return tenantKeyPrefix(region) + tenantName;
}
private static String tenantKeyPrefix(String region) {
return "tenant::" + region + "::";
}
}
@@ -0,0 +1,20 @@
package io.github.hectorvent.floci.services.ses.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
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.
*/
@RegisterForReflection
public record Tenant(String tenantName,
String tenantId,
String tenantArn,
Instant createdTimestamp,
List<Tag> tags,
String sendingStatus) {
}
@@ -15,8 +15,10 @@ import io.github.hectorvent.floci.services.ses.model.Identity;
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.route53.Route53Service;
import java.security.SecureRandom;
import java.time.Clock;
import static org.mockito.Mockito.mock;
@@ -45,6 +47,7 @@ final class SesServiceTestBuilder {
private final InMemoryStorage<String, String> policyStore = new InMemoryStorage<>();
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 SmtpRelay smtpRelay = mock(SmtpRelay.class);
// Default null, matching the production null-Route53 case: SesService treats a null Route53Service
@@ -121,6 +124,7 @@ final class SesServiceTestBuilder {
new SesPolicyService(policyStore, objectMapper),
new SesReceiptRuleService(receiptRuleStore, clock),
new SesCvetService(cvetStore),
new SesTenantService(tenantStore, clock, new SecureRandom()),
smtpRelay,
objectMapper,
route53Service,
@@ -0,0 +1,133 @@
package io.github.hectorvent.floci.services.ses;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.ses.model.Tag;
import io.github.hectorvent.floci.services.ses.model.Tenant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.security.SecureRandom;
import java.time.Clock;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.
*/
class SesTenantServiceTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private SesTenantService service;
@BeforeEach
void setUp() {
service = new SesTenantService(new InMemoryStorage<>(), Clock.systemUTC(), new SecureRandom());
}
@Test
void create_generatesIdAndArn_defaultsSendingEnabled() {
Tenant t = service.createTenant("acme", List.of(new Tag("team", "floci")), ACCOUNT, REGION);
assertEquals("acme", t.tenantName());
assertTrue(t.tenantId().startsWith("tn-"));
assertEquals("tn-".length() + 30, t.tenantId().length());
assertEquals("arn:aws:ses:" + REGION + ":" + ACCOUNT + ":tenant/acme/" + t.tenantId(), t.tenantArn());
assertEquals("ENABLED", t.sendingStatus());
assertEquals(1, t.tags().size());
}
@Test
void create_thenGet_roundTrips() {
service.createTenant("acme", List.of(), ACCOUNT, REGION);
assertEquals("acme", service.getTenant("acme", REGION).tenantName());
}
@Test
void create_duplicateThrows() {
service.createTenant("acme", List.of(), ACCOUNT, REGION);
AwsException e = assertThrows(AwsException.class,
() -> service.createTenant("acme", List.of(), ACCOUNT, REGION));
assertEquals("AlreadyExistsException", e.getErrorCode());
}
@Test
void get_missingThrows() {
AwsException e = assertThrows(AwsException.class, () -> service.getTenant("ghost", REGION));
assertEquals("NotFoundException", e.getErrorCode());
}
@Test
void delete_removesTenant_missingThrows() {
service.createTenant("acme", List.of(), ACCOUNT, REGION);
service.deleteTenant("acme", REGION);
assertThrows(AwsException.class, () -> service.getTenant("acme", REGION));
assertThrows(AwsException.class, () -> service.deleteTenant("acme", REGION));
}
@Test
void list_isPerRegion() {
service.createTenant("a", List.of(), ACCOUNT, REGION);
service.createTenant("b", List.of(), ACCOUNT, REGION);
service.createTenant("other", List.of(), ACCOUNT, "eu-west-1");
List<Tenant> list = service.listTenants(REGION);
assertEquals(2, list.size());
}
@Test
void validate_nullName_mustNotBeNull() {
AwsException e = assertThrows(AwsException.class, () -> service.createTenant(null, List.of(), ACCOUNT, REGION));
assertEquals("BadRequestException", e.getErrorCode());
assertTrue(e.getMessage().contains("Member must not be null"));
}
@Test
void validate_emptyName_smithyMinLength() {
AwsException e = assertThrows(AwsException.class, () -> service.createTenant("", List.of(), ACCOUNT, REGION));
assertEquals("BadRequestException", e.getErrorCode());
assertTrue(e.getMessage().contains("Member must have length greater than or equal to 1"));
}
@Test
void validate_blankName() {
AwsException e = assertThrows(AwsException.class, () -> service.createTenant(" ", List.of(), ACCOUNT, REGION));
assertEquals("TenantName cannot be empty", e.getMessage());
}
@Test
void validate_tooLongName() {
AwsException e = assertThrows(AwsException.class,
() -> service.createTenant("x".repeat(65), List.of(), ACCOUNT, REGION));
assertEquals("TenantName cannot exceed 64 characters.", e.getMessage());
}
@Test
void validate_badChars() {
AwsException e = assertThrows(AwsException.class,
() -> service.createTenant("bad name!", List.of(), ACCOUNT, REGION));
assertTrue(e.getMessage().startsWith("Invalid tenant name <bad name!>:"));
}
@Test
void create_invalidTag_isRejected() {
assertThrows(AwsException.class,
() -> service.createTenant("acme", List.of(new Tag("", "v")), ACCOUNT, REGION));
}
// Per-account isolation is provided transparently by AccountAwareStorageBackend (which
// StorageFactory wraps every store in), not by the tenant key, so it is covered by the core
// storage tests rather than re-tested here — consistent with the other SES resources.
@Test
void getAndDelete_rejectMalformedName() {
// A required, min-length-1 member: a blank name is a BadRequest, not a NotFound.
AwsException g = assertThrows(AwsException.class, () -> service.getTenant("", REGION));
assertEquals("BadRequestException", g.getErrorCode());
AwsException d = assertThrows(AwsException.class, () -> service.deleteTenant(" ", REGION));
assertEquals("BadRequestException", d.getErrorCode());
}
}
@@ -0,0 +1,151 @@
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.matchesPattern;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;
/**
* Integration tests for the SES v2 tenant CRUD (Phase 1): {@code POST /v2/email/tenants} and the
* RPC-style {@code /tenants/get}, {@code /tenants/list}, {@code /tenants/delete}. Shapes, id/ARN
* formats, the ENABLED default, and the validation/duplicate/not-found errors are verified against
* real AWS.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SesTenantV2IntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request";
private static final String TENANT = "floci-it-tenant";
@Test
@Order(1)
void createTenant_returnsGeneratedIdArnAndEnabledStatus() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"TenantName\":\"" + TENANT + "\",\"Tags\":[{\"Key\":\"team\",\"Value\":\"floci\"}]}")
.when().post("/v2/email/tenants").then().statusCode(200)
.body("TenantName", equalTo(TENANT))
.body("TenantId", matchesPattern("tn-[0-9a-f]{30}"))
.body("TenantArn", startsWith("arn:aws:ses:us-east-1:000000000000:tenant/" + TENANT + "/tn-"))
.body("SendingStatus", equalTo("ENABLED"))
.body("Tags[0].Key", equalTo("team"))
.body("CreatedTimestamp", notNullValue());
}
@Test
@Order(2)
void getTenant_returnsTenant() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"TenantName\":\"" + TENANT + "\"}")
.when().post("/v2/email/tenants/get").then().statusCode(200)
.body("Tenant.TenantName", equalTo(TENANT))
.body("Tenant.SendingStatus", equalTo("ENABLED"))
.body("Tenant.TenantId", startsWith("tn-"));
}
@Test
@Order(3)
void listTenants_includesTenantInfoSubset() {
given().contentType("application/json").header("Authorization", AUTH)
.when().post("/v2/email/tenants/list").then().statusCode(200)
.body("Tenants.find { it.TenantName == '" + TENANT + "' }.TenantId", startsWith("tn-"))
.body("Tenants.find { it.TenantName == '" + TENANT + "' }.SendingStatus", equalTo(null));
}
@Test
@Order(4)
void createTenant_duplicate_returnsAlreadyExists() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"TenantName\":\"" + TENANT + "\"}")
.when().post("/v2/email/tenants").then().statusCode(400)
.body("__type", equalTo("AlreadyExistsException"))
.body("message", startsWith("Tenant with name " + TENANT + " already exists in account"));
}
@Test
@Order(5)
void deleteTenant_removesIt() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"TenantName\":\"" + TENANT + "\"}")
.when().post("/v2/email/tenants/delete").then().statusCode(200);
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"TenantName\":\"" + TENANT + "\"}")
.when().post("/v2/email/tenants/get").then().statusCode(404)
.body("__type", equalTo("NotFoundException"))
.body("message", equalTo("The requested tenant <" + TENANT + "> does not exist."));
}
@Test
@Order(6)
void deleteTenant_missing_returnsNotFound() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"TenantName\":\"ghost-tenant\"}")
.when().post("/v2/email/tenants/delete").then().statusCode(404)
.body("__type", equalTo("NotFoundException"));
}
@Test
@Order(7)
void createTenant_invalidName_returnsBadRequest() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"TenantName\":\"bad name!\"}")
.when().post("/v2/email/tenants").then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", startsWith("Invalid tenant name <bad name!>:"));
}
@Test
@Order(8)
void createTenant_tooLongName_returnsBadRequest() {
String longName = "x".repeat(65);
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"TenantName\":\"" + longName + "\"}")
.when().post("/v2/email/tenants").then().statusCode(400)
.body("message", equalTo("TenantName cannot exceed 64 characters."));
}
@Test
@Order(9)
void createTenant_invalidTag_returnsBadRequest() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"TenantName\":\"tag-tenant\",\"Tags\":[{\"Key\":\"\",\"Value\":\"v\"}]}")
.when().post("/v2/email/tenants").then().statusCode(400)
.body("__type", equalTo("BadRequestException"));
}
@Test
@Order(10)
void getTenant_emptyName_returnsBadRequest() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"TenantName\":\"\"}")
.when().post("/v2/email/tenants/get").then().statusCode(400)
.body("__type", equalTo("BadRequestException"));
}
@Test
@Order(11)
void listTenants_malformedBody_returnsSerializationException() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{ not json")
.when().post("/v2/email/tenants/list").then().statusCode(400)
.body("__type", equalTo("SerializationException"));
}
@Test
@Order(12)
void createTenant_nonStringTagMember_returnsSerializationException() {
given().contentType("application/json").header("Authorization", AUTH)
.body("{\"TenantName\":\"nonstring-tag\",\"Tags\":[{\"Key\":123,\"Value\":true}]}")
.when().post("/v2/email/tenants").then().statusCode(400)
.body("__type", equalTo("SerializationException"));
}
}