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

@@ -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) {
}