mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(ses): order the send checks and read v1 bulk destinations like SES (#6490)
* fix(ses): verify the sender before the stored template and tenant associations A tenant-scoped SES v2 send refused an unassociated resource with the 403 before anything else, and SendEmail and SendBulkEmail looked a stored template up before checking the sender. AWS reports a missing configuration set, then an unverified sender or return path, then a missing stored template, and the tenant association 403 last. The tenant lookup and the DISABLED refusal stay early; the template lookup and the association check now run inside the send, after sender verification. SendBulkEmail and SendBulkTemplatedEmail now verify the sender and return path once for the whole call, unless no entry has a recipient. * fix(ses): run the tenant gate inside the send and order v1 bulk like v2 The first half of the tenant gate (lookup and DISABLED refusal) moves from the v2 controller into the send paths, so the association check reuses the tenant it found, and a raw message is read for its X-SES-CONFIGURATION-SET header only when the tenant is DISABLED. v1 SendBulkTemplatedEmail passes its stored template to the send, which looks it up after sender verification as v2 SendBulkEmail does. * fix(ses): read every v1 bulk destination entry like AWS SendBulkTemplatedEmail stopped reading Destinations.member.N at the first entry with no addresses, replacement data or tags. An empty ToAddresses list, which boto3 sends as a bare empty-valued key, ended the list there, so later entries were dropped and a lone empty entry was answered "At least one destination is required." instead of reaching the send. The handler now reads up to the highest member index. A missing Template (with no TemplateArn), missing Destinations, and an entry without a Destination or a skipped index are model violations, answered together as one 400 ValidationError ahead of the address syntax, the template selector and the destination count. In the send, an entry with no recipient beside entries with one fails alone with "Missing required header 'To'." on v1 and v2 alike, while a request in which no entry names a recipient still answers every entry "Destination cannot be empty", ahead of sender verification and the template lookup. All of it was probed. * refactor(ses): build the value-less not-null violation in SmithyValidationErrors Some operations answer a missing member as "Value at '<path>' failed to satisfy constraint: Member must not be null", without the null that SmithyValidationErrors.notNull puts after "Value". SesQueryHandler, SesExportJobService and SesReceiptRuleService each built that text themselves. SmithyValidationErrors.notNullWithoutValue now builds it beside notNull, and the three use it.
This commit is contained in:
1 parent
00e6b0d905
commit
ba82e0aeaa
18 files changed
+1063
-242
No files matched your search
@@ -31,6 +31,11 @@ public final class SmithyValidationErrors {
|
||||
return "Value null at '" + path + "' failed to satisfy constraint: Member must not be null";
|
||||
}
|
||||
|
||||
/** The same violation in the form some operations answer, without {@code null} after "Value". */
|
||||
public static String notNullWithoutValue(String path) {
|
||||
return "Value at '" + path + "' failed to satisfy constraint: Member must not be null";
|
||||
}
|
||||
|
||||
/** The 400 error carrying {@link #message} under the protocol's validation error code. */
|
||||
public static AwsException exception(String errorCode, List<String> violations) {
|
||||
return new AwsException(errorCode, message(violations), 400);
|
||||
|
||||
@@ -137,11 +137,12 @@ public class SesExportJobService implements Resettable {
|
||||
throw new AwsException("BadRequestException", "One data source must be provided", 400);
|
||||
}
|
||||
if (!exportDestination.isObject()) {
|
||||
throw notNull("exportDestination");
|
||||
throw SmithyValidationErrors.badRequest(SmithyValidationErrors.notNullWithoutValue("exportDestination"));
|
||||
}
|
||||
String dataFormat = exportDestination.path("DataFormat").textValue();
|
||||
if (dataFormat == null) {
|
||||
throw notNull("exportDestination.dataFormat");
|
||||
throw SmithyValidationErrors.badRequest(
|
||||
SmithyValidationErrors.notNullWithoutValue("exportDestination.dataFormat"));
|
||||
}
|
||||
if (!DATA_FORMATS.contains(dataFormat)) {
|
||||
throw SmithyValidationErrors.badRequest(
|
||||
@@ -540,11 +541,6 @@ public class SesExportJobService implements Resettable {
|
||||
return ExportJob.FORMAT_CSV.equals(dataFormat) ? "text/csv" : "application/json";
|
||||
}
|
||||
|
||||
private static AwsException notNull(String member) {
|
||||
return SmithyValidationErrors.badRequest(
|
||||
"Value at '" + member + "' failed to satisfy constraint: Member must not be null");
|
||||
}
|
||||
|
||||
/**
|
||||
* The model bounds {@code MaxResults} at 1 to 10000. An unchecked negative value reached
|
||||
* {@code subList} inside the filter and surfaced as a 500. The value is stored as the int it
|
||||
@@ -572,10 +568,8 @@ public class SesExportJobService implements Resettable {
|
||||
private static Instant requireDate(JsonNode source, String field) {
|
||||
Instant value = date(source, field);
|
||||
if (value == null) {
|
||||
throw SmithyValidationErrors.badRequest(
|
||||
"Value at '" + field.substring(0, 1).toLowerCase(Locale.ROOT)
|
||||
+ field.substring(1) + "' failed to satisfy constraint: "
|
||||
+ "Member must not be null");
|
||||
throw SmithyValidationErrors.badRequest(SmithyValidationErrors.notNullWithoutValue(
|
||||
field.substring(0, 1).toLowerCase(Locale.ROOT) + field.substring(1)));
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
@@ -38,9 +38,11 @@ import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Query-protocol handler for SES actions.
|
||||
@@ -764,12 +766,33 @@ public class SesQueryHandler {
|
||||
throw new AwsException("AccountSendingPausedException",
|
||||
"Account sending is disabled.", 400);
|
||||
}
|
||||
String templateName = getParam(params, "Template");
|
||||
String templateArn = getParam(params, "TemplateArn");
|
||||
BulkDestinationIndexes destinations = bulkDestinationIndexes(params);
|
||||
// The model validation answers ahead of every other check of the request, listing its
|
||||
// violations in the model's member order (probe-confirmed).
|
||||
List<String> violations = new ArrayList<>();
|
||||
if (templateName == null && templateArn == null) {
|
||||
violations.add(SmithyValidationErrors.notNullWithoutValue("template"));
|
||||
}
|
||||
if (!params.containsKey("Destinations") && !hasParamWithPrefix(params, "Destinations.")) {
|
||||
violations.add(SmithyValidationErrors.notNullWithoutValue("destinations"));
|
||||
}
|
||||
// A skipped index, like an entry without a Destination, is a null destination
|
||||
// (probe-confirmed). An empty address list still sends its bare key.
|
||||
for (int i = 1; i <= Math.min(destinations.last(), MAX_VALIDATED_DESTINATION_INDEX); i++) {
|
||||
if (!destinations.withDestination().contains(i)) {
|
||||
violations.add(SmithyValidationErrors.notNullWithoutValue("destinations." + i + ".member.destination"));
|
||||
}
|
||||
}
|
||||
if (!violations.isEmpty()) {
|
||||
throw SmithyValidationErrors.validationError(violations);
|
||||
}
|
||||
|
||||
String source = getParam(params, "Source");
|
||||
SesAddressSyntax.requireBulkAddress(source);
|
||||
SesAddressSyntax.requireBulkAddress(getParam(params, "ReturnPath"));
|
||||
List<String> replyToAddresses = extractMembers(params, "ReplyToAddresses");
|
||||
String templateName = getParam(params, "Template");
|
||||
String templateArn = getParam(params, "TemplateArn");
|
||||
String defaultDataRaw = getParam(params, "DefaultTemplateData");
|
||||
|
||||
boolean hasName = templateName != null && !templateName.isBlank();
|
||||
@@ -780,28 +803,25 @@ public class SesQueryHandler {
|
||||
}
|
||||
String resolvedName = hasName ? templateName : SesTemplateService.templateNameFromArn(templateArn);
|
||||
|
||||
int lastIndex = destinations.last();
|
||||
if (lastIndex == 0) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"At least one destination is required.", 400);
|
||||
}
|
||||
// AWS counts the destinations before it looks the template up (probe-confirmed). The list
|
||||
// runs to its highest index, so counting that index first also bounds the scan below.
|
||||
SesService.requireBulkDestinationCount(lastIndex);
|
||||
List<BulkEmailEntry> entries = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
for (int i = 1; i <= lastIndex; i++) {
|
||||
String destPrefix = "Destinations.member." + i;
|
||||
List<String> to = extractMembers(params, destPrefix + ".Destination.ToAddresses");
|
||||
List<String> cc = extractMembers(params, destPrefix + ".Destination.CcAddresses");
|
||||
List<String> bcc = extractMembers(params, destPrefix + ".Destination.BccAddresses");
|
||||
String replacementRaw = getParam(params, destPrefix + ".ReplacementTemplateData");
|
||||
List<MessageTag> replacementTags = extractMessageTags(params, destPrefix + ".ReplacementTags");
|
||||
if (to.isEmpty() && cc.isEmpty() && bcc.isEmpty()
|
||||
&& replacementRaw == null && replacementTags.isEmpty()) {
|
||||
break;
|
||||
}
|
||||
entries.add(new BulkEmailEntry(to, cc, bcc,
|
||||
parseTemplateData(replacementRaw), replacementTags, List.of()));
|
||||
}
|
||||
if (entries.isEmpty()) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"At least one destination is required.", 400);
|
||||
}
|
||||
// AWS counts the destinations before it looks the template up (probe-confirmed).
|
||||
SesService.requireBulkDestinationCount(entries.size());
|
||||
EmailTemplate template = templateService.getTemplate(resolvedName, region);
|
||||
JsonNode defaultTemplateData = parseTemplateData(defaultDataRaw);
|
||||
|
||||
String configurationSetName = getParam(params, "ConfigurationSetName");
|
||||
@@ -809,13 +829,14 @@ public class SesQueryHandler {
|
||||
List<MessageTag> defaultEmailTags = extractMessageTags(params, "DefaultTags");
|
||||
List<BulkEmailEntryResult> results = sesService.sendBulkEmail(SendBulkEmailRequest.builder()
|
||||
.source(source)
|
||||
.sourceArn(getParam(params, "SourceArn"))
|
||||
.replyToAddresses(replyToAddresses)
|
||||
.returnPath(returnPath)
|
||||
.returnPathArn(getParam(params, "ReturnPathArn"))
|
||||
.configurationSetName(configurationSetName)
|
||||
.defaultEmailTags(defaultEmailTags)
|
||||
.region(region)
|
||||
.defaultContent(new EmailContent.InlineTemplate(template.getSubject(), template.getTextPart(),
|
||||
template.getHtmlPart(), defaultTemplateData, List.of()))
|
||||
.defaultContent(new EmailContent.Template(resolvedName, defaultTemplateData, List.of()))
|
||||
.entries(entries)
|
||||
.build());
|
||||
|
||||
@@ -1558,6 +1579,46 @@ public class SesQueryHandler {
|
||||
|
||||
// --- Helpers ---
|
||||
|
||||
private static boolean hasParamWithPrefix(MultivaluedMap<String, String> params, String prefix) {
|
||||
return params.keySet().stream().anyMatch(key -> key.startsWith(prefix));
|
||||
}
|
||||
|
||||
// Bounds the violation list a hostile index could inflate; an index above it still fails the
|
||||
// destination count. Where AWS stops listing null destinations has not been probed.
|
||||
private static final int MAX_VALIDATED_DESTINATION_INDEX = 1000;
|
||||
|
||||
/** The highest {@code Destinations.member.N}, and the Ns that carry a {@code Destination}. */
|
||||
private record BulkDestinationIndexes(int last, Set<Integer> withDestination) {}
|
||||
|
||||
private static BulkDestinationIndexes bulkDestinationIndexes(MultivaluedMap<String, String> params) {
|
||||
String prefix = "Destinations.member.";
|
||||
int last = 0;
|
||||
Set<Integer> withDestination = new HashSet<>();
|
||||
for (String key : params.keySet()) {
|
||||
if (!key.startsWith(prefix)) {
|
||||
continue;
|
||||
}
|
||||
int dot = key.indexOf('.', prefix.length());
|
||||
int index = memberIndex(dot < 0 ? key.substring(prefix.length()) : key.substring(prefix.length(), dot));
|
||||
if (index == 0) {
|
||||
continue;
|
||||
}
|
||||
last = Math.max(last, index);
|
||||
if (dot >= 0 && key.startsWith(".Destination.", dot)) {
|
||||
withDestination.add(index);
|
||||
}
|
||||
}
|
||||
return new BulkDestinationIndexes(last, withDestination);
|
||||
}
|
||||
|
||||
// 0 for a token that is not a member index; one too long for an int is past any limit.
|
||||
private static int memberIndex(String token) {
|
||||
if (token.isEmpty() || token.charAt(0) == '0' || !token.chars().allMatch(c -> c >= '0' && c <= '9')) {
|
||||
return 0;
|
||||
}
|
||||
return token.length() > 9 ? Integer.MAX_VALUE : Integer.parseInt(token);
|
||||
}
|
||||
|
||||
private List<String> extractMembers(MultivaluedMap<String, String> params, String prefix) {
|
||||
List<String> members = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
|
||||
@@ -751,25 +751,24 @@ public class SesReceiptRuleService {
|
||||
*/
|
||||
private static void validateFilterShape(ReceiptFilter filter) {
|
||||
if (filter == null) {
|
||||
throw SmithyValidationErrors.validationError(
|
||||
notNullViolation("filter"));
|
||||
throw SmithyValidationErrors.validationError(SmithyValidationErrors.notNullWithoutValue("filter"));
|
||||
}
|
||||
List<String> violations = new ArrayList<>();
|
||||
if (filter.getName() == null) {
|
||||
violations.add(notNullViolation("filter.name"));
|
||||
violations.add(SmithyValidationErrors.notNullWithoutValue("filter.name"));
|
||||
}
|
||||
boolean hasIpFilter = filter.getPolicy() != null || filter.getCidr() != null;
|
||||
if (!hasIpFilter) {
|
||||
violations.add(notNullViolation("filter.ipFilter"));
|
||||
violations.add(SmithyValidationErrors.notNullWithoutValue("filter.ipFilter"));
|
||||
} else {
|
||||
if (filter.getPolicy() == null) {
|
||||
violations.add(notNullViolation("filter.ipFilter.policy"));
|
||||
violations.add(SmithyValidationErrors.notNullWithoutValue("filter.ipFilter.policy"));
|
||||
} else if (!"Allow".equals(filter.getPolicy()) && !"Block".equals(filter.getPolicy())) {
|
||||
violations.add("Value at 'filter.ipFilter.policy' failed to satisfy constraint: "
|
||||
+ "Member must satisfy enum value set: [Allow, Block]");
|
||||
}
|
||||
if (filter.getCidr() == null) {
|
||||
violations.add(notNullViolation("filter.ipFilter.cidr"));
|
||||
violations.add(SmithyValidationErrors.notNullWithoutValue("filter.ipFilter.cidr"));
|
||||
}
|
||||
}
|
||||
if (!violations.isEmpty()) {
|
||||
@@ -777,10 +776,6 @@ public class SesReceiptRuleService {
|
||||
}
|
||||
}
|
||||
|
||||
private static String notNullViolation(String path) {
|
||||
return "Value at '" + path + "' failed to satisfy constraint: Member must not be null";
|
||||
}
|
||||
|
||||
/**
|
||||
* Service-level filter name checks, probed: empty gets its own message, and every other
|
||||
* malformed shape (bad character, longer than 64, non-alphanumeric start or end) shares
|
||||
|
||||
@@ -11,7 +11,6 @@ import io.github.hectorvent.floci.services.ses.address.SesAddressSyntax;
|
||||
import io.github.hectorvent.floci.services.ses.model.BulkEmailEntry;
|
||||
import io.github.hectorvent.floci.services.ses.model.BulkEmailEntryResult;
|
||||
import io.github.hectorvent.floci.services.ses.model.EmailContent;
|
||||
import io.github.hectorvent.floci.services.ses.model.EmailTemplate;
|
||||
import io.github.hectorvent.floci.services.ses.model.ListManagementOptions;
|
||||
import io.github.hectorvent.floci.services.ses.model.MessageAttachment;
|
||||
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
|
||||
@@ -49,8 +48,7 @@ import static io.github.hectorvent.floci.services.ses.SesV2Json.remapV1Exception
|
||||
* {@code /v2/email/outbound-custom-verification-emails}. Every other v2 URL group has its own
|
||||
* controller in this package; the send path stays here because it is the one group that reads
|
||||
* across several domains. It goes through the {@link SesService} facade for that reason, and
|
||||
* through {@link SesTemplateService} and {@link SesAccountService} for the stored template and
|
||||
* the account-level sending switch.
|
||||
* through {@link SesAccountService} for the account-level sending switch.
|
||||
*/
|
||||
@Path("/v2/email")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@@ -62,19 +60,15 @@ public class SesSendController {
|
||||
private static final List<String> TRACKING_VALUES = List.of("ENABLED", "DISABLED");
|
||||
|
||||
private final SesService sesService;
|
||||
// The bulk send resolves a stored template's content before handing the entries to the facade.
|
||||
private final SesTemplateService templateService;
|
||||
// The send endpoints read the account-level sending switch before building the message.
|
||||
private final SesAccountService accountService;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public SesSendController(SesService sesService, SesTemplateService templateService,
|
||||
SesAccountService accountService, RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper) {
|
||||
public SesSendController(SesService sesService, SesAccountService accountService,
|
||||
RegionResolver regionResolver, ObjectMapper objectMapper) {
|
||||
this.sesService = sesService;
|
||||
this.templateService = templateService;
|
||||
this.accountService = accountService;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
@@ -143,8 +137,6 @@ public class SesSendController {
|
||||
}
|
||||
requireNoNullAddress(toAddresses, ccAddresses, bccAddresses, replyToAddresses);
|
||||
SendEmailRequest rawRequest = sendRequest.content(new EmailContent.Raw(rawData, true)).build();
|
||||
sesService.checkTenantRawSendAccess(tenantName, fromEmailAddress, rawData,
|
||||
rawRequest.hasRecipients(), configurationSetName, regionResolver.getAccountId(), region);
|
||||
messageId = sesService.sendEmail(rawRequest);
|
||||
} else if (content.has("Simple")) {
|
||||
if (fromEmailAddress == null || fromEmailAddress.isBlank()) {
|
||||
@@ -164,7 +156,6 @@ public class SesSendController {
|
||||
.content(new EmailContent.Simple(subject, bodyText, bodyHtml, additionalHeaders,
|
||||
attachments))
|
||||
.build();
|
||||
sesService.checkTenantSendAccess(simpleRequest, null, regionResolver.getAccountId());
|
||||
messageId = sesService.sendEmail(simpleRequest);
|
||||
} else if (content.has("Template")) {
|
||||
if (fromEmailAddress == null || fromEmailAddress.isBlank()) {
|
||||
@@ -197,7 +188,6 @@ public class SesSendController {
|
||||
SendEmailRequest templateRequest = sendRequest
|
||||
.content(new EmailContent.Template(resolvedName, templateData, additionalHeaders))
|
||||
.build();
|
||||
sesService.checkTenantSendAccess(templateRequest, resolvedName, regionResolver.getAccountId());
|
||||
messageId = sesService.sendEmail(templateRequest);
|
||||
} else {
|
||||
JsonNode inline = template.path("TemplateContent");
|
||||
@@ -213,7 +203,6 @@ public class SesSendController {
|
||||
.content(new EmailContent.InlineTemplate(subject, text, html, templateData,
|
||||
additionalHeaders))
|
||||
.build();
|
||||
sesService.checkTenantSendAccess(inlineRequest, null, regionResolver.getAccountId());
|
||||
messageId = sesService.sendEmail(inlineRequest);
|
||||
}
|
||||
} else {
|
||||
@@ -288,28 +277,23 @@ public class SesSendController {
|
||||
String subject = null;
|
||||
String text = null;
|
||||
String html = null;
|
||||
// Inline template content is not a stored template resource, so it stays out of the
|
||||
// tenant gate below.
|
||||
String gateTemplateName = null;
|
||||
// The send looks the stored template up only after its sender checks (probe-confirmed).
|
||||
String storedTemplateName = 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.
|
||||
// Shape validation belongs before the send's tenant lookup, as on SendEmail.
|
||||
SesService.requireInlineTemplateContent(subject, text, html);
|
||||
}
|
||||
// AWS counts the entries after the inline content check and before it looks the stored
|
||||
// template up (probe-confirmed).
|
||||
SesService.requireBulkDestinationCount(bulkEntries.size());
|
||||
if (!hasInline) {
|
||||
String resolvedName = hasName
|
||||
storedTemplateName = hasName
|
||||
? templateName
|
||||
: SesTemplateService.templateNameFromArn(templateArn);
|
||||
gateTemplateName = resolvedName;
|
||||
subject = null;
|
||||
text = null;
|
||||
html = null;
|
||||
}
|
||||
|
||||
JsonNode defaultTemplateData = parseTemplateData(template, "TemplateData");
|
||||
@@ -337,28 +321,23 @@ public class SesSendController {
|
||||
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.checkTenantBulkSendAccess(tenantName, fromEmailAddress, configurationSetName,
|
||||
gateTemplateName, entries, regionResolver.getAccountId(), region);
|
||||
// SES reports an unknown or DISABLED tenant before an unknown stored template (probe-confirmed).
|
||||
if (gateTemplateName != null) {
|
||||
EmailTemplate stored = templateService.getTemplate(gateTemplateName, region);
|
||||
subject = stored.getSubject();
|
||||
text = stored.getTextPart();
|
||||
html = stored.getHtmlPart();
|
||||
}
|
||||
// The send looks the tenant up, so only after every part of the request has been parsed
|
||||
// and validated: AWS reports malformed content before a missing tenant (probe-confirmed).
|
||||
EmailContent.TemplateContent defaultContent = storedTemplateName == null
|
||||
? new EmailContent.InlineTemplate(subject, text, html, defaultTemplateData, defaultHeaders)
|
||||
: new EmailContent.Template(storedTemplateName, defaultTemplateData, defaultHeaders);
|
||||
|
||||
List<BulkEmailEntryResult> results = sesService.sendBulkEmail(SendBulkEmailRequest.builder()
|
||||
.source(fromEmailAddress)
|
||||
.sourceArn(request.path("FromEmailAddressIdentityArn").asText(null))
|
||||
.replyToAddresses(replyToAddresses)
|
||||
.returnPath(feedbackForwardingAddress)
|
||||
.returnPathArn(request.path("FeedbackForwardingEmailAddressIdentityArn").asText(null))
|
||||
.configurationSetName(configurationSetName)
|
||||
.defaultEmailTags(defaultEmailTags)
|
||||
.tenantName(tenantName)
|
||||
.region(region)
|
||||
.defaultContent(new EmailContent.InlineTemplate(subject, text, html, defaultTemplateData,
|
||||
defaultHeaders))
|
||||
.defaultContent(defaultContent)
|
||||
.entries(entries)
|
||||
.build());
|
||||
|
||||
|
||||
@@ -52,6 +52,7 @@ import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
@@ -275,16 +276,23 @@ public class SesService {
|
||||
if (request.content() instanceof EmailContent.Raw raw) {
|
||||
return sendRawEmail(request, raw, requireVerifiedSender);
|
||||
}
|
||||
Tenant tenant = requireSendingTenant(request.tenantName(), request.region(), request,
|
||||
request::configurationSetName);
|
||||
if (request.content() instanceof EmailContent.InlineTemplate inline) {
|
||||
requireInlineTemplateContent(inline.subject(), inline.textPart(), inline.htmlPart());
|
||||
}
|
||||
// After a missing sender, AWS reports a malformed address ahead of the destination and
|
||||
// configuration-set checks, then an over-long address, and only then a missing stored
|
||||
// template (probe-confirmed), so the content is resolved after these checks.
|
||||
// configuration-set checks, then an over-long address, then an unverified sender, and only
|
||||
// then a missing stored template (probe-confirmed), so the content is resolved last.
|
||||
requireSource(request);
|
||||
SesAddressSyntax.requireEnvelope(request);
|
||||
String effectiveConfigSet = validateEnvelope(request);
|
||||
SesAddressLength.requireEnvelope(request);
|
||||
if (requireVerifiedSender) {
|
||||
requireVerifiedSenders(List.of(
|
||||
new SendingAddress(request.source(), request.sourceArn()),
|
||||
new SendingAddress(request.returnPath(), request.returnPathArn())), request.region());
|
||||
}
|
||||
EmailContent.Simple content = switch (request.content()) {
|
||||
case EmailContent.Simple simple -> simple;
|
||||
case EmailContent.Template template ->
|
||||
@@ -292,11 +300,10 @@ public class SesService {
|
||||
case EmailContent.InlineTemplate inline -> SesTemplateService.render(inline);
|
||||
case EmailContent.Raw raw -> throw new IllegalStateException("Raw content is sent above");
|
||||
};
|
||||
if (requireVerifiedSender) {
|
||||
requireVerifiedSenders(List.of(
|
||||
new SendingAddress(request.source(), request.sourceArn()),
|
||||
new SendingAddress(request.returnPath(), request.returnPathArn())), request.region());
|
||||
}
|
||||
String templateName = request.content() instanceof EmailContent.Template template
|
||||
? template.templateName()
|
||||
: null;
|
||||
requireTenantAssociations(tenant, request.source(), effectiveConfigSet, templateName, request.region());
|
||||
return sendSimpleEmail(request.toBuilder().content(content).build(), content, effectiveConfigSet);
|
||||
}
|
||||
|
||||
@@ -309,9 +316,10 @@ public class SesService {
|
||||
|
||||
// "The message must be sent from a verified email address or domain" (API_SendEmail), and the
|
||||
// error "could apply to the "From", "Source", "Sender", or "Return-Path" address" (developer
|
||||
// guide, Email sending errors). It runs after the request's own validation so that
|
||||
// probe-confirmed order is unchanged; where AWS places this check among those errors has not
|
||||
// been probed.
|
||||
// guide, Email sending errors). It runs after the request's own validation: a missing
|
||||
// configuration set is reported ahead of an unverified sender, and an unverified sender or
|
||||
// return path ahead of a missing stored template and a tenant association 403 (probe-confirmed
|
||||
// on v2). Where AWS places it among the other validation errors has not been probed.
|
||||
private void requireVerifiedSenders(List<SendingAddress> senders, String region) {
|
||||
String accountId = callerAccountId();
|
||||
// A blank address is not used, and neither is the null reverse-path "<>".
|
||||
@@ -527,6 +535,11 @@ public class SesService {
|
||||
private String sendRawEmail(SendEmailRequest request, EmailContent.Raw raw, boolean requireVerifiedSender) {
|
||||
String source = request.source();
|
||||
String region = request.region();
|
||||
// The configuration set checked before a DISABLED refusal may be named by the
|
||||
// X-SES-CONFIGURATION-SET header alone, so the message is read for it only on that path.
|
||||
Tenant tenant = requireSendingTenant(request.tenantName(), region, null,
|
||||
() -> firstNonBlank(request.configurationSetName(),
|
||||
SmtpRelay.parseRawHeaders(raw.data()).configurationSet()));
|
||||
if (raw.data() == null || raw.data().isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "RawMessage.Data is required.", 400);
|
||||
}
|
||||
@@ -576,6 +589,7 @@ public class SesService {
|
||||
if (requireVerifiedSender) {
|
||||
requireVerifiedSenders(rawSendingAddresses(request, raw, headers), region);
|
||||
}
|
||||
requireTenantAssociations(tenant, effectiveSource, effectiveConfigSet, null, region);
|
||||
// Resolve suppression before recording the message so a bad ListManagementOptions (e.g. an
|
||||
// unknown contact list) fails the whole send without leaving an orphaned SentEmail record.
|
||||
Map<String, String> suppressedReasons = new LinkedHashMap<>(
|
||||
@@ -1134,71 +1148,47 @@ public class SesService {
|
||||
}
|
||||
|
||||
/**
|
||||
* The tenant send gate (Phase 4): resolves the tenant with the send-flavored not-found wording,
|
||||
* refuses a tenant whose sending is DISABLED, then requires every resource the send uses to be
|
||||
* associated with it. Placement is probe-confirmed: request-shape validation (a missing Content,
|
||||
* an empty inline template, a missing FromEmailAddress on Simple, the bulk template-content
|
||||
* checks) runs before the tenant lookup, while the recipient checks, the raw MIME-From
|
||||
* derivation, and identity verification all lose to the tenant 404. The DISABLED refusal also
|
||||
* beats identity verification, the association check and a raw message's missing recipients,
|
||||
* but an unknown configuration set named by the request is reported before it, and so are the
|
||||
* address and recipient checks of a Simple or Template send, which goes through the overload
|
||||
* that takes its envelope.
|
||||
* The first half of the tenant send gate, run where each send starts: resolves the
|
||||
* tenant with the send-flavored not-found wording and refuses a tenant whose sending is DISABLED,
|
||||
* or returns null for a send with no tenant. Placement is probe-confirmed: request-shape
|
||||
* validation (a missing Content, an empty inline template, a missing FromEmailAddress on Simple,
|
||||
* the bulk template-content checks) runs before the tenant lookup, while the recipient checks,
|
||||
* the raw MIME-From derivation, and identity verification all lose to the tenant 404. The
|
||||
* DISABLED refusal also beats identity verification, the association check and a raw message's
|
||||
* missing recipients, but the configuration set the request names is looked up before it, and
|
||||
* a Simple or Template send's {@code envelope} has its address and recipient checks run first.
|
||||
* The association half runs at the end of the send, see {@code requireTenantAssociations}.
|
||||
*/
|
||||
public void checkTenantSendAccess(String tenantName, String fromEmailAddress,
|
||||
String configurationSetName, String templateName,
|
||||
String accountId, String region) {
|
||||
checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName, templateName, accountId,
|
||||
region, null, configurationSetName);
|
||||
}
|
||||
|
||||
/**
|
||||
* The send gate for SendBulkEmail, which refuses a DISABLED tenant before it looks up the
|
||||
* configuration set, unlike SendEmail. A request in which no entry names a recipient skips the
|
||||
* gate altogether, even for an unknown tenant: each entry is answered on its own instead
|
||||
* (probe-confirmed).
|
||||
*/
|
||||
public void checkTenantBulkSendAccess(String tenantName, String fromEmailAddress,
|
||||
String configurationSetName, String templateName,
|
||||
List<BulkEmailEntry> entries, String accountId, String region) {
|
||||
if (!anyBulkRecipient(entries)) {
|
||||
return;
|
||||
}
|
||||
checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName, templateName, accountId,
|
||||
region, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The send gate for a Simple or Template send, whose envelope SES validates before it refuses a
|
||||
* DISABLED tenant: a malformed address and a request with no recipient are reported first
|
||||
* (probe-confirmed), while a tenant that may send still meets the gate before them.
|
||||
*/
|
||||
public void checkTenantSendAccess(SendEmailRequest envelope, String templateName, String accountId) {
|
||||
checkTenantSendAccess(envelope.tenantName(), envelope.source(), envelope.configurationSetName(),
|
||||
templateName, accountId, envelope.region(), envelope, envelope.configurationSetName());
|
||||
}
|
||||
|
||||
private void checkTenantSendAccess(String tenantName, String fromEmailAddress,
|
||||
String configurationSetName, String templateName,
|
||||
String accountId, String region, SendEmailRequest envelope,
|
||||
String configurationSetBeforeRefusal) {
|
||||
private Tenant requireSendingTenant(String tenantName, String region, SendEmailRequest envelope,
|
||||
Supplier<String> configurationSetBeforeRefusal) {
|
||||
if (tenantName == null) {
|
||||
return null;
|
||||
}
|
||||
Tenant tenant = tenantService.tenantForSending(tenantName, region, callerAccountId());
|
||||
requireSendingEnabled(tenant, configurationSetBeforeRefusal, region, envelope);
|
||||
return tenant;
|
||||
}
|
||||
|
||||
// The second half of the tenant send gate, and the last check of a send: AWS reports a missing
|
||||
// configuration set or stored template and an unverified sender or return path ahead of the 403
|
||||
// (probe-confirmed). Every resource the send uses must be associated with the tenant: the
|
||||
// sender's identity, the effective configuration set (an omitted name resolves to the sender
|
||||
// identity's default, which needs the association just as an explicit one does) and the stored
|
||||
// template.
|
||||
private void requireTenantAssociations(Tenant tenant, String source, String effectiveConfigSet,
|
||||
String templateName, String region) {
|
||||
if (tenant == null) {
|
||||
return;
|
||||
}
|
||||
Tenant tenant = tenantService.tenantForSending(tenantName, region, accountId);
|
||||
requireSendingEnabled(tenant, configurationSetBeforeRefusal, region, envelope);
|
||||
String arnPrefix = "arn:" + AwsRegions.partitionFor(region) + ":ses:" + region + ":" + accountId + ":";
|
||||
String arnPrefix = "arn:" + AwsRegions.partitionFor(region) + ":ses:" + region + ":" + callerAccountId()
|
||||
+ ":";
|
||||
List<SesTenantService.AssociationResource> used = new ArrayList<>();
|
||||
if (fromEmailAddress != null && !fromEmailAddress.isBlank()) {
|
||||
String identityName = sendIdentityName(fromEmailAddress, region);
|
||||
if (source != null && !source.isBlank()) {
|
||||
String identityName = sendIdentityName(source, 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,
|
||||
@@ -1212,41 +1202,7 @@ public class SesService {
|
||||
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.
|
||||
* {@code hasDestination} says whether the request named any recipient; when it did not and the
|
||||
* MIME To, Cc and Bcc headers are empty too, only the tenant's existence and sending status
|
||||
* are checked.
|
||||
*/
|
||||
public void checkTenantRawSendAccess(String tenantName, String fromEmailAddress,
|
||||
String rawMessage, boolean hasDestination,
|
||||
String configurationSetName, String accountId, String region) {
|
||||
if (tenantName == null) {
|
||||
return;
|
||||
}
|
||||
SmtpRelay.RawMessageHeaders headers = SmtpRelay.parseRawHeaders(rawMessage);
|
||||
// AWS checks that the tenant exists and may send, then reports a message with no recipients
|
||||
// anywhere ahead of the association gate (probe-confirmed), so that error is left to
|
||||
// sendRawEmail.
|
||||
if (!hasDestination && SendEmailRequest.recipients(headers.to(), headers.cc(), headers.bcc()).isEmpty()) {
|
||||
requireSendingEnabled(tenantService.tenantForSending(tenantName, region, accountId),
|
||||
firstNonBlank(configurationSetName, headers.configurationSet()), region, null);
|
||||
return;
|
||||
}
|
||||
String effectiveSource = fromEmailAddress;
|
||||
if (effectiveSource == null || effectiveSource.isBlank()) {
|
||||
effectiveSource = headers.from().isBlank() ? null : headers.from();
|
||||
}
|
||||
// The gate sees the same configuration set the send will use, so one named only by the
|
||||
// X-SES-CONFIGURATION-SET header cannot slip past the tenant association check.
|
||||
checkTenantSendAccess(tenantName, effectiveSource,
|
||||
firstNonBlank(configurationSetName, headers.configurationSet()), null,
|
||||
accountId, region);
|
||||
}
|
||||
|
||||
private void requireSendingEnabled(Tenant tenant, String configurationSetName, String region,
|
||||
private void requireSendingEnabled(Tenant tenant, Supplier<String> configurationSetName, String region,
|
||||
SendEmailRequest envelope) {
|
||||
if (!"DISABLED".equals(tenant.sendingStatus())) {
|
||||
return;
|
||||
@@ -1255,8 +1211,9 @@ public class SesService {
|
||||
SesAddressSyntax.requireEnvelope(envelope);
|
||||
requireRecipients(envelope);
|
||||
}
|
||||
if (configurationSetName != null && !configurationSetName.isBlank()) {
|
||||
configSetService.get(configurationSetName, region);
|
||||
String configurationSet = configurationSetName.get();
|
||||
if (configurationSet != null && !configurationSet.isBlank()) {
|
||||
configSetService.get(configurationSet, region);
|
||||
}
|
||||
throw new AwsException("MessageRejected", "Sending disabled for <" + tenant.tenantArn()
|
||||
+ ">. For more information, please check the resource configuration and status.", 400);
|
||||
@@ -1728,12 +1685,19 @@ public class SesService {
|
||||
}
|
||||
|
||||
public List<BulkEmailEntryResult> sendBulkEmail(SendBulkEmailRequest request) {
|
||||
EmailContent.InlineTemplate template = request.defaultContent();
|
||||
if (request.source() == null || request.source().isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "Source email is required.", 400);
|
||||
}
|
||||
requireInlineTemplateContent(template.subject(), template.textPart(), template.htmlPart());
|
||||
if (request.defaultContent() instanceof EmailContent.InlineTemplate inline) {
|
||||
requireInlineTemplateContent(inline.subject(), inline.textPart(), inline.htmlPart());
|
||||
}
|
||||
requireBulkDestinationCount(sizeOf(request.entries()));
|
||||
// SendBulkEmail refuses a DISABLED tenant before it looks up the configuration set, unlike
|
||||
// SendEmail, and a request in which no entry names a recipient skips the gate altogether,
|
||||
// even for an unknown tenant: each entry is answered on its own instead (probe-confirmed).
|
||||
Tenant tenant = anyBulkRecipient(request.entries())
|
||||
? requireSendingTenant(request.tenantName(), request.region(), null, () -> null)
|
||||
: null;
|
||||
configSetService.validateForSending(request.configurationSetName(), request.region());
|
||||
for (BulkEmailEntry entry : request.entries()) {
|
||||
int recipientCount = sizeOf(entry.toAddresses())
|
||||
@@ -1754,10 +1718,27 @@ public class SesService {
|
||||
"Destination cannot be empty"))
|
||||
.toList();
|
||||
}
|
||||
// The sender and return path are checked once for the whole call, then a stored template is
|
||||
// looked up, then the tenant associations, as on a single send (probe-confirmed).
|
||||
requireVerifiedSenders(List.of(
|
||||
new SendingAddress(request.source(), request.sourceArn()),
|
||||
new SendingAddress(request.returnPath(), request.returnPathArn())), request.region());
|
||||
EmailContent.InlineTemplate template = switch (request.defaultContent()) {
|
||||
case EmailContent.Template stored -> templateService.inline(stored, request.region());
|
||||
case EmailContent.InlineTemplate inline -> inline;
|
||||
};
|
||||
requireTenantAssociations(tenant, request.source(),
|
||||
resolveDefaultConfigurationSet(request.configurationSetName(), request.source(), request.region()),
|
||||
request.templateName(), request.region());
|
||||
List<BulkEmailEntryResult> results = new ArrayList<>(request.entries().size());
|
||||
for (BulkEmailEntry entry : request.entries()) {
|
||||
try {
|
||||
SesAddressSyntax.requireBulkDestination(entry, request.replyToAddresses());
|
||||
// An entry with no recipient beside entries with one fails on its own (probe-confirmed
|
||||
// on v1 and v2).
|
||||
if (!anyBulkRecipient(List.of(entry))) {
|
||||
throw new AwsException("InvalidParameterValue", "Missing required header 'To'.", 400);
|
||||
}
|
||||
JsonNode merged = mergeTemplateData(template.templateData(), entry.replacementTemplateData());
|
||||
List<MessageTag> mergedTags = mergeEmailTags(request.defaultEmailTags(), entry.replacementEmailTags());
|
||||
List<MessageHeader> mergedHeaders = mergeHeaders(template.headers(), entry.replacementHeaders());
|
||||
@@ -1780,8 +1761,8 @@ public class SesService {
|
||||
.build();
|
||||
// SesAddressLength is not applied to entries: an over-long bulk destination did not
|
||||
// fail the length check ahead of sender verification (probe-confirmed; the
|
||||
// verified-sender case is unprobed). The bulk sender and return path are checked
|
||||
// by requireBulkAddress.
|
||||
// verified-sender case is unprobed). The bulk sender and return path were checked
|
||||
// above, their syntax by requireBulkAddress and their verification once for the call.
|
||||
String messageId = sendSimpleEmail(entryRequest, rendered, validateEnvelope(entryRequest));
|
||||
results.add(BulkEmailEntryResult.success(messageId));
|
||||
} catch (AwsException e) {
|
||||
|
||||
@@ -36,12 +36,18 @@ public sealed interface EmailContent {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The two template variants, the only content a bulk send's default content can be.
|
||||
*/
|
||||
sealed interface TemplateContent extends EmailContent {
|
||||
}
|
||||
|
||||
record Template(String templateName, JsonNode templateData, List<MessageHeader> headers)
|
||||
implements EmailContent {
|
||||
implements TemplateContent {
|
||||
}
|
||||
|
||||
record InlineTemplate(String subject, String textPart, String htmlPart, JsonNode templateData,
|
||||
List<MessageHeader> headers) implements EmailContent {
|
||||
List<MessageHeader> headers) implements TemplateContent {
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+22
-8
@@ -6,56 +6,70 @@ import java.util.Objects;
|
||||
/**
|
||||
* The service-level input of a bulk send, shaped like the v2 {@code SendBulkEmailRequest}: an
|
||||
* envelope, the default template every entry renders, and the per-destination entries. The
|
||||
* controllers resolve a stored template before building it, so the default content is always
|
||||
* {@link EmailContent.InlineTemplate}; its data and headers are the defaults each entry's
|
||||
* replacements merge over.
|
||||
* default content is a stored {@link EmailContent.Template}, which the send resolves only after its
|
||||
* sender checks, or an {@link EmailContent.InlineTemplate}; its data and headers are the defaults
|
||||
* each entry's replacements merge over. {@code sourceArn} and {@code returnPathArn} are the
|
||||
* sending-authorization identity ARNs of the sender and the return path.
|
||||
*/
|
||||
public record SendBulkEmailRequest(
|
||||
String source,
|
||||
String sourceArn,
|
||||
List<String> replyToAddresses,
|
||||
String returnPath,
|
||||
String returnPathArn,
|
||||
String configurationSetName,
|
||||
List<MessageTag> defaultEmailTags,
|
||||
String tenantName,
|
||||
String region,
|
||||
EmailContent.InlineTemplate defaultContent,
|
||||
EmailContent.TemplateContent defaultContent,
|
||||
List<BulkEmailEntry> entries) {
|
||||
|
||||
public SendBulkEmailRequest {
|
||||
Objects.requireNonNull(defaultContent, "defaultContent");
|
||||
}
|
||||
|
||||
/**
|
||||
* The name of the stored template the default content names, or {@code null} for inline content.
|
||||
*/
|
||||
public String templateName() {
|
||||
return defaultContent instanceof EmailContent.Template stored ? stored.templateName() : null;
|
||||
}
|
||||
|
||||
public static Builder builder() {
|
||||
return new Builder();
|
||||
}
|
||||
|
||||
public static final class Builder {
|
||||
private String source;
|
||||
private String sourceArn;
|
||||
private List<String> replyToAddresses = List.of();
|
||||
private String returnPath;
|
||||
private String returnPathArn;
|
||||
private String configurationSetName;
|
||||
private List<MessageTag> defaultEmailTags = List.of();
|
||||
private String tenantName;
|
||||
private String region;
|
||||
private EmailContent.InlineTemplate defaultContent;
|
||||
private EmailContent.TemplateContent defaultContent;
|
||||
private List<BulkEmailEntry> entries = List.of();
|
||||
|
||||
private Builder() {
|
||||
}
|
||||
|
||||
public Builder source(String source) { this.source = source; return this; }
|
||||
public Builder sourceArn(String sourceArn) { this.sourceArn = sourceArn; return this; }
|
||||
public Builder replyToAddresses(List<String> replyToAddresses) { this.replyToAddresses = replyToAddresses; return this; }
|
||||
public Builder returnPath(String returnPath) { this.returnPath = returnPath; return this; }
|
||||
public Builder returnPathArn(String returnPathArn) { this.returnPathArn = returnPathArn; return this; }
|
||||
public Builder configurationSetName(String configurationSetName) { this.configurationSetName = configurationSetName; return this; }
|
||||
public Builder defaultEmailTags(List<MessageTag> defaultEmailTags) { this.defaultEmailTags = defaultEmailTags; return this; }
|
||||
public Builder tenantName(String tenantName) { this.tenantName = tenantName; return this; }
|
||||
public Builder region(String region) { this.region = region; return this; }
|
||||
public Builder defaultContent(EmailContent.InlineTemplate defaultContent) { this.defaultContent = defaultContent; return this; }
|
||||
public Builder defaultContent(EmailContent.TemplateContent defaultContent) { this.defaultContent = defaultContent; return this; }
|
||||
public Builder entries(List<BulkEmailEntry> entries) { this.entries = entries; return this; }
|
||||
|
||||
public SendBulkEmailRequest build() {
|
||||
return new SendBulkEmailRequest(source, replyToAddresses, returnPath, configurationSetName,
|
||||
defaultEmailTags, tenantName, region, defaultContent, entries);
|
||||
return new SendBulkEmailRequest(source, sourceArn, replyToAddresses, returnPath, returnPathArn,
|
||||
configurationSetName, defaultEmailTags, tenantName, region, defaultContent, entries);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user