feat(ses): support v2 tenant-scoped sending with association gate (#2815)

* feat(ses): support v2 tenant-scoped sending with association gate

* fix(ses): guard tenantForSending against a null TenantName and pin the raw-test charset

* fix(ses): validate an inline bulk template before the tenant gate
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-08-31 09:35:40 -04:00
1 parent 5b363ffa2d
commit b0fe8311a0
7 files changed
+511 -16

No files matched your search

@@ -504,6 +504,7 @@ public class SesController {
List<String> replyToAddresses = jsonArrayToList(request.path("ReplyToAddresses"));
List<String> allDestinations = mergeLists(toAddresses, ccAddresses, bccAddresses);
String configurationSetName = request.path("ConfigurationSetName").asText(null);
String tenantName = stringMemberOrAbsent(request, "TenantName");
List<MessageTag> emailTags = parseEmailTagsArray(request.path("EmailTags"), "EmailTags");
ListManagementOptions listManagement =
parseListManagementOptions(request.path("ListManagementOptions"));
@@ -521,6 +522,8 @@ public class SesController {
throw new AwsException("BadRequestException",
"At least one destination address is required.", 400);
}
sesService.checkTenantRawSendAccess(tenantName, fromEmailAddress, rawData,
configurationSetName, regionResolver.getAccountId(), region);
messageId = sesService.sendRawEmail(fromEmailAddress, allDestinations, rawData,
configurationSetName, emailTags, listManagement, region);
} else if (content.has("Simple")) {
@@ -534,6 +537,8 @@ public class SesController {
String bodyHtml = simple.path("Body").path("Html").path("Data").asText(null);
List<MessageHeader> additionalHeaders =
parseHeadersArray(simple.path("Headers"), "content.simple.headers");
sesService.checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName,
null, regionResolver.getAccountId(), region);
messageId = sesService.sendEmail(fromEmailAddress, toAddresses, ccAddresses,
bccAddresses, replyToAddresses, subject, bodyText, bodyHtml,
configurationSetName, emailTags, additionalHeaders, listManagement, region);
@@ -564,6 +569,8 @@ public class SesController {
String resolvedName = hasName
? templateName
: SesService.templateNameFromArn(templateArn);
sesService.checkTenantSendAccess(tenantName, fromEmailAddress,
configurationSetName, resolvedName, regionResolver.getAccountId(), region);
messageId = sesService.sendTemplatedEmail(fromEmailAddress, toAddresses, ccAddresses,
bccAddresses, replyToAddresses, resolvedName, templateData,
configurationSetName, emailTags, additionalHeaders, listManagement, region);
@@ -572,6 +579,12 @@ public class SesController {
String subject = inline.path("Subject").asText(null);
String text = inline.path("Text").asText(null);
String html = inline.path("Html").asText(null);
// An empty inline template is reported before the tenant lookup on AWS; the
// inline content is not a stored template resource, so only the identity and
// configuration set pass through the gate.
SesService.requireInlineTemplateContent(subject, text, html);
sesService.checkTenantSendAccess(tenantName, fromEmailAddress,
configurationSetName, null, regionResolver.getAccountId(), region);
messageId = sesService.sendInlineTemplatedEmail(fromEmailAddress, toAddresses,
ccAddresses, bccAddresses, replyToAddresses,
subject, text, html, templateData,
@@ -614,6 +627,7 @@ public class SesController {
}
List<String> replyToAddresses = jsonArrayToList(request.path("ReplyToAddresses"));
String configurationSetName = request.path("ConfigurationSetName").asText(null);
String tenantName = stringMemberOrAbsent(request, "TenantName");
JsonNode template = request.path("DefaultContent").path("Template");
if (template.isMissingNode() || template.isNull()) {
@@ -639,15 +653,21 @@ public class SesController {
String subject;
String text;
String html;
// Inline template content is not a stored template resource, so it stays out of the
// tenant gate below.
String gateTemplateName = null;
if (hasInline) {
JsonNode inline = template.path("TemplateContent");
subject = inline.path("Subject").asText(null);
text = inline.path("Text").asText(null);
html = inline.path("Html").asText(null);
// Shape validation belongs before the tenant gate below, as on SendEmail.
SesService.requireInlineTemplateContent(subject, text, html);
} else {
String resolvedName = hasName
? templateName
: SesService.templateNameFromArn(templateArn);
gateTemplateName = resolvedName;
EmailTemplate stored = sesService.getTemplate(resolvedName, region);
subject = stored.getSubject();
text = stored.getTextPart();
@@ -686,6 +706,11 @@ public class SesController {
entryIndex++;
}
// The tenant gate runs only after every part of the request has been parsed and
// validated — AWS reports malformed content before a missing tenant (probe-confirmed).
sesService.checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName,
gateTemplateName, regionResolver.getAccountId(), region);
List<BulkEmailEntryResult> results = sesService.sendBulkTemplatedEmail(fromEmailAddress,
replyToAddresses, subject, text, html,
defaultTemplateData, entries, configurationSetName,
@@ -1728,6 +1728,88 @@ public class SesService {
return tenantService.listResourceTenants(ref, region);
}
/**
* The tenant send gate (Phase 4): resolves the tenant with the send-flavored not-found wording,
* then requires every resource the send uses to be associated with it. The tenant's
* SendingStatus is not checked — no API can move it off ENABLED, so the DISABLED gate is not
* emulated. Placement is probe-confirmed: request-shape validation (a missing Content, an empty
* inline template, a missing FromEmailAddress on Simple, the bulk template-content checks) runs
* before the tenant lookup, while the recipient checks, the raw MIME-From derivation, and
* identity verification all lose to the tenant 404.
*/
public void checkTenantSendAccess(String tenantName, String fromEmailAddress,
String configurationSetName, String templateName,
String accountId, String region) {
if (tenantName == null) {
return;
}
Tenant tenant = tenantService.tenantForSending(tenantName, region, accountId);
String arnPrefix = "arn:aws:ses:" + region + ":" + accountId + ":";
List<SesTenantService.AssociationResource> used = new ArrayList<>();
if (fromEmailAddress != null && !fromEmailAddress.isBlank()) {
String identityName = sendIdentityName(fromEmailAddress, region);
used.add(new SesTenantService.AssociationResource(
SesTenantService.RESOURCE_TYPE_IDENTITY, identityName,
arnPrefix + "identity/" + identityName));
}
// The gate covers the EFFECTIVE configuration set: an omitted name resolves to the sender
// identity's default, and that one needs the association just as an explicit one does.
String effectiveConfigSet =
resolveDefaultConfigurationSet(configurationSetName, fromEmailAddress, region);
if (effectiveConfigSet != null && !effectiveConfigSet.isBlank()) {
used.add(new SesTenantService.AssociationResource(
SesTenantService.RESOURCE_TYPE_CONFIGURATION_SET, effectiveConfigSet,
arnPrefix + "configuration-set/" + effectiveConfigSet));
}
if (templateName != null && !templateName.isBlank()) {
used.add(new SesTenantService.AssociationResource(
SesTenantService.RESOURCE_TYPE_TEMPLATE, templateName,
arnPrefix + "template/" + templateName));
}
tenantService.requireResourcesAssociated(tenant, used, region);
}
/**
* The raw-content variant of the tenant send gate: when {@code FromEmailAddress} is omitted,
* the effective sender comes from the MIME {@code From} header — the same derivation
* {@code sendRawEmail} applies — so the gate must resolve it the same way before checking.
*/
public void checkTenantRawSendAccess(String tenantName, String fromEmailAddress,
String rawMessage, String configurationSetName,
String accountId, String region) {
if (tenantName == null) {
return;
}
String effectiveSource = fromEmailAddress;
if (effectiveSource == null || effectiveSource.isBlank()) {
SmtpRelay.RawMessageHeaders headers = SmtpRelay.parseRawHeaders(rawMessage);
effectiveSource = headers != null && !headers.from().isBlank() ? headers.from() : null;
}
checkTenantSendAccess(tenantName, effectiveSource, configurationSetName, null,
accountId, region);
}
// The gate names the identity the way AWS did in the probed error: the exact address identity
// when one exists, otherwise the domain identity the address falls under. The sender may carry
// display-name syntax ("Name <a@b>"), so the bare address is extracted first.
private String sendIdentityName(String fromEmailAddress, String region) {
String email = extractEmailAddress(fromEmailAddress);
if (email.isBlank()) {
return fromEmailAddress.trim();
}
if (identityStore.get(identityKey(region, email)).isPresent()) {
return email;
}
int at = email.lastIndexOf('@');
if (at >= 0) {
String domain = email.substring(at + 1);
if (identityStore.get(identityKey(region, domain)).isPresent()) {
return domain;
}
}
return email;
}
// 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) {
@@ -2812,13 +2894,12 @@ public class SesService {
return "===_floci_" + HexFormat.of().formatHex(bytes) + "_===";
}
public String sendInlineTemplatedEmail(String source, List<String> toAddresses, List<String> ccAddresses,
List<String> bccAddresses, List<String> replyToAddresses,
String subject, String textPart, String htmlPart,
JsonNode templateData,
String configurationSetName, List<MessageTag> emailTags,
List<MessageHeader> additionalHeaders,
ListManagementOptions listManagement, String region) {
/**
* Also called by the controller ahead of the tenant send gate: AWS reports an empty inline
* template before it looks the tenant up (probe-confirmed), so the check must not stay behind
* the gate for tenant sends.
*/
static void requireInlineTemplateContent(String subject, String textPart, String htmlPart) {
boolean hasSubject = subject != null && !subject.isBlank();
boolean hasText = textPart != null && !textPart.isBlank();
boolean hasHtml = htmlPart != null && !htmlPart.isBlank();
@@ -2826,6 +2907,16 @@ public class SesService {
throw new AwsException("InvalidTemplate",
"Template must have at least a subject, text, or html part.", 400);
}
}
public String sendInlineTemplatedEmail(String source, List<String> toAddresses, List<String> ccAddresses,
List<String> bccAddresses, List<String> replyToAddresses,
String subject, String textPart, String htmlPart,
JsonNode templateData,
String configurationSetName, List<MessageTag> emailTags,
List<MessageHeader> additionalHeaders,
ListManagementOptions listManagement, String region) {
requireInlineTemplateContent(subject, textPart, htmlPart);
return sendEmail(source, toAddresses, ccAddresses, bccAddresses, replyToAddresses,
applyTemplateData(subject, templateData),
applyTemplateData(textPart, templateData),
@@ -2845,13 +2936,7 @@ public class SesService {
if (source == null || source.isBlank()) {
throw new AwsException("InvalidParameterValue", "Source email is required.", 400);
}
boolean hasSubject = subject != null && !subject.isBlank();
boolean hasText = textPart != null && !textPart.isBlank();
boolean hasHtml = htmlPart != null && !htmlPart.isBlank();
if (!hasSubject && !hasText && !hasHtml) {
throw new AwsException("InvalidTemplate",
"Template must have at least a subject, text, or html part.", 400);
}
requireInlineTemplateContent(subject, textPart, htmlPart);
if (entries == null || entries.isEmpty()) {
throw new AwsException("InvalidParameterValue",
"At least one destination entry is required.", 400);
@@ -193,6 +193,43 @@ public class SesTenantService {
.orElseThrow(() -> tenantNotFound(tenantName));
}
// ──────────────────────── Tenant-scoped sending (Phase 4) ────────────────────────
// Behavior and messages probe-confirmed against real AWS us-east-1, 2026-08-30.
/**
* Resolves the tenant for a send. The not-found wording differs from the management operations:
* no angle brackets, and the account id is included.
*/
public Tenant tenantForSending(String tenantName, String region, String accountId) {
// Unreachable through the facade (which treats a null TenantName as a non-tenant send), but
// a public helper should fail the AWS way — same guard as runWithTenant.
if (tenantName == null || tenantName.isBlank()) {
throw new AwsException("BadRequestException", "TenantName cannot be empty", 400);
}
return tenantStore.get(tenantKey(region, tenantName))
.orElseThrow(() -> new AwsException("NotFoundException",
"Tenant " + tenantName + " for AwsAccountId " + accountId + " not found.", 404));
}
/**
* The send gate: every resource a tenant send uses (From identity, configuration set, template)
* must be associated with the tenant, or AWS refuses the send with a 403. The bracket list
* carries every missing ARN (the plural is AWS's own wording even for a single resource; on the
* wire AWS spells the body key "Message" — Floci renders its usual error shape instead).
*/
public void requireResourcesAssociated(Tenant tenant, List<AssociationResource> resources,
String region) {
List<String> missing = resources.stream()
.filter(ref -> associationStore
.get(associationKey(region, tenant.tenantId(), ref)).isEmpty())
.map(AssociationResource::arn)
.toList();
if (!missing.isEmpty()) {
throw new AwsException("AccessDeniedException",
"Tenant not associated with resources [" + String.join(", ", missing) + "].", 403);
}
}
/**
* 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