mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(ses): publish SES events to SNS configuration set destinations (#1106)
* feat(ses): publish SES events to SNS configuration set destinations Add SES V2 event publishing to SnsDestination targets configured on a ConfigurationSet. When SendEmail / SendRawEmail / SendTemplatedEmail / SendBulkEmail is invoked with a ConfigurationSetName, Floci builds the matching AWS-format event payload (a `mail` block plus an event-type- specific block) and publishes it to each enabled SNS destination whose MatchingEventTypes includes that event. Events emitted - SEND on every successful send. - DELIVERY / BOUNCE / COMPLAINT / REJECT when a recipient matches the corresponding AWS mailbox simulator address (success@ / bounce@ / complaint@ / suppressionlist@simulator.amazonses.com). - Per-event-type recipient lists (delivery.recipients, bounce.bouncedRecipients, complaint.complainedRecipients) are filtered to only the simulator address that triggered the event and emitted in their canonical trimmed form; mail.destination carries the full envelope. Wire-level fidelity - Event payload mirrors the AWS SES SNS notification format documented at https://docs.aws.amazon.com/ses/latest/dg/event-publishing-retrieving-sns-examples.html. - mail.tags includes user-supplied EmailTags / DefaultEmailTags / ReplacementTags (V2) and Tags.member.N / DefaultTags.member.N / Destinations.member.N.ReplacementTags (V1 Query). Each tag emits as {Name: [Value]}. - mail.headers[] appends user-supplied Content.Simple.Headers and Content.Template.Headers after the auto-emitted From/To/Cc/Subject; null/blank Names are rejected with "The header name must be specified." (BadRequestException 400). - V2 SendBulkEmail BulkEmailEntries accept ReplacementTags (merged by Name onto DefaultEmailTags) and ReplacementHeaders (merged case-insensitively per RFC 5322 onto DefaultContent.Template.Headers). - mail.sendingAccountId resolves from EmulatorConfig.defaultAccountId(). - ConfigurationSet existence is validated up-front on sendEmail / sendRawEmail / sendBulkTemplatedEmail — an unknown name fails fast with ConfigurationSetDoesNotExist (V2 controller remaps to NotFoundException 404, V1 returns 400) before any message is stored or relayed. Validation errors aligned with live AWS - EmailTags blank Name: BadRequestException 400 "The tag name must be specified." (V2) / InvalidParameterValue 400 same message (V1). - ConfigurationSetName not found: same error code, status, and message as AWS. Raw email handling - For V2 SendEmail with Raw content (and V1 SendRawEmail), when the caller did not provide Destinations, Floci falls back to To/Cc/Bcc parsed from the raw MIME via SmtpRelay.parseRawHeaders (extracted from the existing relay logic). MIME parsing is only invoked when needed (no explicit Destinations or event publishing active). Internal shape - New records: model/MessageTag (Name, Value, for EmailTags) and model/MessageHeader (Name, Value, for Content.Headers) — kept distinct from the resource-tag Tag (Key, Value). - SesEventPublisher dispatches to SnsService; non-SNS destination types log a warning and are skipped (Firehose / EventBridge / CloudWatch / Pinpoint), and missing SnsDestination.TopicArn likewise warns instead of silently dropping. Failures preserve the throwable in the warn log. Tests - SesEventPayloadTest covers mail/commonHeaders/headers/tags shape, per-event filtering, and the headers/tags propagation paths. - SesServiceMergeEmailTagsTest / SesServiceMergeHeadersTest pin Bulk Default vs per-entry merge semantics (tags by Name case-sensitive, headers by Name case-insensitive per RFC 5322). - SesEventPublishingV2IntegrationTest exercises Send / Delivery / Bounce / SendOnly / mixed-recipient / disabled-destination / V1-MIME-fallback / EmailTags / V1-Tags / Simple.Headers paths end-to-end through SES -> SNS -> SQS. - compatibility-tests/sdk-test-java/SesEventPublishingTest validates SendEmail with EmailTags/Headers and SendBulkEmail with per-entry ReplacementHeaders override using AWS Java SDK V2 clients. * fix(ses): address Copilot review on upstream PR #1106 - SesService.validateConfigurationSet: clarify the Javadoc — the helper always throws with httpStatus = 400, and the V2 controller's remapV1Exception is what turns ConfigurationSetDoesNotExist into NotFoundException 404. The previous "(404 in V2, 400 in V1)" hint read as if the helper itself picked the status, which is misleading. - SesController.parseEmailTagsArray: reject non-object entries with "<fieldName> entries must be JSON objects.", mirroring the existing parseHeadersArray check. Previously a string/number element would hit the blank-Name path and report a less specific message. - SesService.mergeHeaders / mergeEmailTags: also skip entries whose name is the empty string, not just null. Both parsers reject blank names at the boundary, but defending the merge helpers keeps them safe for direct callers (e.g., future tests) and matches the intent of the boundary validation.
This commit is contained in:
1 parent
d33d6b67c0
commit
35211adc4a
19 files changed
+2184
-32
No files matched your search
@@ -9,6 +9,8 @@ import io.github.hectorvent.floci.services.ses.model.ConfigurationSet;
|
||||
import io.github.hectorvent.floci.services.ses.model.EmailTemplate;
|
||||
import io.github.hectorvent.floci.services.ses.model.EventDestination;
|
||||
import io.github.hectorvent.floci.services.ses.model.Identity;
|
||||
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
|
||||
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.Tag;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
@@ -271,6 +273,9 @@ public class SesController {
|
||||
List<String> ccAddresses = jsonArrayToList(destination.path("CcAddresses"));
|
||||
List<String> bccAddresses = jsonArrayToList(destination.path("BccAddresses"));
|
||||
List<String> replyToAddresses = jsonArrayToList(request.path("ReplyToAddresses"));
|
||||
List<String> allDestinations = mergeLists(toAddresses, ccAddresses, bccAddresses);
|
||||
String configurationSetName = request.path("ConfigurationSetName").asText(null);
|
||||
List<MessageTag> emailTags = parseEmailTagsArray(request.path("EmailTags"), "EmailTags");
|
||||
|
||||
JsonNode content = request.path("Content");
|
||||
String messageId;
|
||||
@@ -281,19 +286,21 @@ public class SesController {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Content.Raw.Data is required.", 400);
|
||||
}
|
||||
List<String> allDestinations = mergeLists(toAddresses, ccAddresses, bccAddresses);
|
||||
if (allDestinations.isEmpty()) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"At least one destination address is required.", 400);
|
||||
}
|
||||
messageId = sesService.sendRawEmail(fromEmailAddress, allDestinations, rawData, region);
|
||||
messageId = sesService.sendRawEmail(fromEmailAddress, allDestinations, rawData,
|
||||
configurationSetName, emailTags, region);
|
||||
} else if (content.has("Simple")) {
|
||||
JsonNode simple = content.path("Simple");
|
||||
String subject = simple.path("Subject").path("Data").asText("");
|
||||
String bodyText = simple.path("Body").path("Text").path("Data").asText(null);
|
||||
String bodyHtml = simple.path("Body").path("Html").path("Data").asText(null);
|
||||
List<MessageHeader> additionalHeaders = parseHeadersArray(simple.path("Headers"));
|
||||
messageId = sesService.sendEmail(fromEmailAddress, toAddresses, ccAddresses,
|
||||
bccAddresses, replyToAddresses, subject, bodyText, bodyHtml, region);
|
||||
bccAddresses, replyToAddresses, subject, bodyText, bodyHtml,
|
||||
configurationSetName, emailTags, additionalHeaders, region);
|
||||
} else if (content.has("Template")) {
|
||||
JsonNode template = content.path("Template");
|
||||
String templateName = template.path("TemplateName").asText(null);
|
||||
@@ -312,12 +319,14 @@ public class SesController {
|
||||
"Content.Template requires TemplateName, TemplateArn, or TemplateContent.", 400);
|
||||
}
|
||||
JsonNode templateData = parseTemplateData(template, "TemplateData");
|
||||
List<MessageHeader> additionalHeaders = parseHeadersArray(template.path("Headers"));
|
||||
if (hasName || hasArn) {
|
||||
String resolvedName = hasName
|
||||
? templateName
|
||||
: SesService.templateNameFromArn(templateArn);
|
||||
messageId = sesService.sendTemplatedEmail(fromEmailAddress, toAddresses, ccAddresses,
|
||||
bccAddresses, replyToAddresses, resolvedName, templateData, region);
|
||||
bccAddresses, replyToAddresses, resolvedName, templateData,
|
||||
configurationSetName, emailTags, additionalHeaders, region);
|
||||
} else {
|
||||
JsonNode inline = template.path("TemplateContent");
|
||||
String subject = inline.path("Subject").asText(null);
|
||||
@@ -325,7 +334,8 @@ public class SesController {
|
||||
String html = inline.path("Html").asText(null);
|
||||
messageId = sesService.sendInlineTemplatedEmail(fromEmailAddress, toAddresses,
|
||||
ccAddresses, bccAddresses, replyToAddresses,
|
||||
subject, text, html, templateData, region);
|
||||
subject, text, html, templateData,
|
||||
configurationSetName, emailTags, additionalHeaders, region);
|
||||
}
|
||||
} else {
|
||||
throw new AwsException("BadRequestException",
|
||||
@@ -363,6 +373,7 @@ public class SesController {
|
||||
"FromEmailAddress is required.", 400);
|
||||
}
|
||||
List<String> replyToAddresses = jsonArrayToList(request.path("ReplyToAddresses"));
|
||||
String configurationSetName = request.path("ConfigurationSetName").asText(null);
|
||||
|
||||
JsonNode template = request.path("DefaultContent").path("Template");
|
||||
if (template.isMissingNode() || template.isNull()) {
|
||||
@@ -404,6 +415,8 @@ public class SesController {
|
||||
}
|
||||
|
||||
JsonNode defaultTemplateData = parseTemplateData(template, "TemplateData");
|
||||
List<MessageTag> defaultEmailTags = parseEmailTagsArray(request.path("DefaultEmailTags"), "DefaultEmailTags");
|
||||
List<MessageHeader> defaultHeaders = parseHeadersArray(template.path("Headers"));
|
||||
|
||||
JsonNode bulkEntries = request.path("BulkEmailEntries");
|
||||
if (!bulkEntries.isArray() || bulkEntries.isEmpty()) {
|
||||
@@ -424,12 +437,15 @@ public class SesController {
|
||||
JsonNode replacementContent = requireObjectOrAbsent(node, "ReplacementEmailContent");
|
||||
JsonNode replacementTemplate = requireObjectOrAbsent(replacementContent, "ReplacementTemplate");
|
||||
JsonNode replacementData = parseTemplateData(replacementTemplate, "ReplacementTemplateData");
|
||||
entries.add(new BulkEmailEntry(to, cc, bcc, replacementData));
|
||||
List<MessageTag> replacementTags = parseEmailTagsArray(node.path("ReplacementTags"), "ReplacementTags");
|
||||
List<MessageHeader> entryReplacementHeaders = parseHeadersArray(node.path("ReplacementHeaders"));
|
||||
entries.add(new BulkEmailEntry(to, cc, bcc, replacementData, replacementTags, entryReplacementHeaders));
|
||||
}
|
||||
|
||||
List<BulkEmailEntryResult> results = sesService.sendBulkTemplatedEmail(fromEmailAddress,
|
||||
replyToAddresses, subject, text, html,
|
||||
defaultTemplateData, entries, region);
|
||||
defaultTemplateData, entries, configurationSetName,
|
||||
defaultEmailTags, defaultHeaders, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode arr = response.putArray("BulkEmailEntryResults");
|
||||
@@ -1179,6 +1195,69 @@ public class SesController {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a V2 SES {@code Content.Simple.Headers} / {@code Content.Template.Headers} array
|
||||
* (additional message headers, elements use {@code Name}/{@code Value}). Returns an empty
|
||||
* list when the node is absent so callers can pass it through unconditionally.
|
||||
*/
|
||||
private List<MessageHeader> parseHeadersArray(JsonNode headersNode) {
|
||||
if (headersNode.isMissingNode() || headersNode.isNull()) {
|
||||
return List.of();
|
||||
}
|
||||
if (!headersNode.isArray()) {
|
||||
throw new AwsException("BadRequestException", "Headers must be an array.", 400);
|
||||
}
|
||||
List<MessageHeader> out = new ArrayList<>();
|
||||
for (JsonNode h : headersNode) {
|
||||
if (!h.isObject()) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Headers entries must be JSON objects.", 400);
|
||||
}
|
||||
String name = h.path("Name").asText(null);
|
||||
String value = h.path("Value").asText(null);
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"The header name must be specified.", 400);
|
||||
}
|
||||
out.add(new MessageHeader(name, value));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a V2 SES {@code EmailTags} / {@code DefaultEmailTags} / {@code ReplacementTags}
|
||||
* array (per-message {@link MessageTag} list whose elements use {@code Name}/{@code Value},
|
||||
* distinct from the resource-tag {@link Tag} {@code Key}/{@code Value} shape). Note that
|
||||
* the per-entry name is {@code ReplacementTags} on the wire — only the top-level field
|
||||
* carries the {@code EmailTags} suffix. Returns an empty list when the node is absent so
|
||||
* callers can pass it through unconditionally.
|
||||
* The {@code fieldName} parameter is reported in the error message when the node is
|
||||
* present but not an array.
|
||||
*/
|
||||
private List<MessageTag> parseEmailTagsArray(JsonNode tagsNode, String fieldName) {
|
||||
if (tagsNode.isMissingNode() || tagsNode.isNull()) {
|
||||
return List.of();
|
||||
}
|
||||
if (!tagsNode.isArray()) {
|
||||
throw new AwsException("BadRequestException", fieldName + " must be an array.", 400);
|
||||
}
|
||||
List<MessageTag> out = new ArrayList<>();
|
||||
for (JsonNode t : tagsNode) {
|
||||
if (!t.isObject()) {
|
||||
throw new AwsException("BadRequestException",
|
||||
fieldName + " entries must be JSON objects.", 400);
|
||||
}
|
||||
String name = t.path("Name").asText(null);
|
||||
String value = t.path("Value").asText(null);
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"The tag name must be specified.", 400);
|
||||
}
|
||||
out.add(new MessageTag(name, value));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static AwsException remapV1Exception(AwsException e) {
|
||||
return switch (e.getErrorCode()) {
|
||||
case "InvalidParameterValue", "InvalidTemplate",
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
|
||||
import io.github.hectorvent.floci.services.ses.model.MessageTag;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Builds the AWS SES event-publishing JSON for a single sent message.
|
||||
*
|
||||
* <p>The output shape matches the SES SNS notification format documented at
|
||||
* https://docs.aws.amazon.com/ses/latest/dg/event-publishing-retrieving-sns-contents.html
|
||||
* — an outer {@code eventType} plus a {@code mail} object and an event-type
|
||||
* specific body block.
|
||||
*/
|
||||
final class SesEventPayload {
|
||||
|
||||
private static final DateTimeFormatter ISO_MILLIS =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC);
|
||||
|
||||
private static final DateTimeFormatter RFC_5322_DATE =
|
||||
DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH)
|
||||
.withZone(ZoneOffset.UTC);
|
||||
|
||||
private SesEventPayload() {}
|
||||
|
||||
static ObjectNode build(ObjectMapper mapper, String eventType, String messageId, String source,
|
||||
String sourceArn, String sendingAccountId, String subject,
|
||||
List<String> toAddresses, List<String> ccAddresses,
|
||||
List<String> bccAddresses, List<String> envelopeDestinations,
|
||||
String configurationSetName, List<MessageTag> emailTags,
|
||||
List<MessageHeader> additionalHeaders, Instant timestamp) {
|
||||
ObjectNode root = mapper.createObjectNode();
|
||||
root.put("eventType", eventTypeLabel(eventType));
|
||||
root.set("mail", buildMail(mapper, messageId, source, sourceArn, sendingAccountId,
|
||||
subject, toAddresses, ccAddresses, bccAddresses, envelopeDestinations,
|
||||
configurationSetName, emailTags, additionalHeaders, timestamp));
|
||||
root.set(blockName(eventType),
|
||||
buildEventBlock(mapper, eventType, messageId, envelopeDestinations, timestamp));
|
||||
return root;
|
||||
}
|
||||
|
||||
private static ObjectNode buildMail(ObjectMapper mapper, String messageId, String source,
|
||||
String sourceArn, String sendingAccountId,
|
||||
String subject, List<String> toAddresses,
|
||||
List<String> ccAddresses, List<String> bccAddresses,
|
||||
List<String> envelopeDestinations,
|
||||
String configurationSetName, List<MessageTag> emailTags,
|
||||
List<MessageHeader> additionalHeaders,
|
||||
Instant timestamp) {
|
||||
ObjectNode mail = mapper.createObjectNode();
|
||||
mail.put("timestamp", ISO_MILLIS.format(timestamp));
|
||||
if (source != null && !source.isBlank()) {
|
||||
mail.put("source", source);
|
||||
}
|
||||
if (sourceArn != null) {
|
||||
mail.put("sourceArn", sourceArn);
|
||||
}
|
||||
mail.put("sendingAccountId", sendingAccountId);
|
||||
mail.put("messageId", messageId);
|
||||
ArrayNode dest = mail.putArray("destination");
|
||||
for (String d : envelopeDestinations) {
|
||||
dest.add(d);
|
||||
}
|
||||
mail.put("headersTruncated", false);
|
||||
ArrayNode headers = mail.putArray("headers");
|
||||
if (source != null && !source.isBlank()) {
|
||||
addHeader(headers, mapper, "From", source);
|
||||
}
|
||||
if (toAddresses != null && !toAddresses.isEmpty()) {
|
||||
addHeader(headers, mapper, "To", String.join(", ", toAddresses));
|
||||
}
|
||||
if (ccAddresses != null && !ccAddresses.isEmpty()) {
|
||||
addHeader(headers, mapper, "Cc", String.join(", ", ccAddresses));
|
||||
}
|
||||
if (subject != null && !subject.isEmpty()) {
|
||||
addHeader(headers, mapper, "Subject", subject);
|
||||
}
|
||||
if (additionalHeaders != null) {
|
||||
for (MessageHeader h : additionalHeaders) {
|
||||
if (h == null || h.name() == null || h.name().isBlank()) {
|
||||
continue;
|
||||
}
|
||||
addHeader(headers, mapper, h.name(), h.value() == null ? "" : h.value());
|
||||
}
|
||||
}
|
||||
ObjectNode common = mail.putObject("commonHeaders");
|
||||
common.put("messageId", messageId);
|
||||
common.put("date", RFC_5322_DATE.format(timestamp));
|
||||
ArrayNode fromArr = common.putArray("from");
|
||||
if (source != null && !source.isBlank()) {
|
||||
fromArr.add(source);
|
||||
}
|
||||
ArrayNode toArr = common.putArray("to");
|
||||
if (toAddresses != null) {
|
||||
for (String a : toAddresses) {
|
||||
toArr.add(a);
|
||||
}
|
||||
}
|
||||
if (ccAddresses != null && !ccAddresses.isEmpty()) {
|
||||
ArrayNode ccArr = common.putArray("cc");
|
||||
for (String a : ccAddresses) {
|
||||
ccArr.add(a);
|
||||
}
|
||||
}
|
||||
if (bccAddresses != null && !bccAddresses.isEmpty()) {
|
||||
ArrayNode bccArr = common.putArray("bcc");
|
||||
for (String a : bccAddresses) {
|
||||
bccArr.add(a);
|
||||
}
|
||||
}
|
||||
if (subject != null && !subject.isEmpty()) {
|
||||
common.put("subject", subject);
|
||||
}
|
||||
ObjectNode tags = mail.putObject("tags");
|
||||
if (configurationSetName != null) {
|
||||
ArrayNode csTag = tags.putArray("ses:configuration-set");
|
||||
csTag.add(configurationSetName);
|
||||
}
|
||||
if (emailTags != null) {
|
||||
for (MessageTag t : emailTags) {
|
||||
if (t == null || t.name() == null) {
|
||||
continue;
|
||||
}
|
||||
ArrayNode arr = tags.has(t.name())
|
||||
? (ArrayNode) tags.get(t.name())
|
||||
: tags.putArray(t.name());
|
||||
arr.add(t.value() == null ? "" : t.value());
|
||||
}
|
||||
}
|
||||
return mail;
|
||||
}
|
||||
|
||||
private static void addHeader(ArrayNode headers, ObjectMapper mapper, String name, String value) {
|
||||
ObjectNode h = mapper.createObjectNode();
|
||||
h.put("name", name);
|
||||
h.put("value", value);
|
||||
headers.add(h);
|
||||
}
|
||||
|
||||
private static ObjectNode buildEventBlock(ObjectMapper mapper, String eventType, String messageId,
|
||||
List<String> destination, Instant timestamp) {
|
||||
ObjectNode body = mapper.createObjectNode();
|
||||
switch (eventType) {
|
||||
case "DELIVERY" -> {
|
||||
body.put("timestamp", ISO_MILLIS.format(timestamp));
|
||||
body.put("processingTimeMillis", 0);
|
||||
ArrayNode recipients = body.putArray("recipients");
|
||||
for (String d : destination) {
|
||||
if (SimulatorAddresses.isSuccess(d)) {
|
||||
recipients.add(d.trim());
|
||||
}
|
||||
}
|
||||
body.put("smtpResponse", "250 ok");
|
||||
body.put("reportingMTA", "floci");
|
||||
}
|
||||
case "BOUNCE" -> {
|
||||
body.put("bounceType", "Permanent");
|
||||
body.put("bounceSubType", "General");
|
||||
ArrayNode bounced = body.putArray("bouncedRecipients");
|
||||
for (String d : destination) {
|
||||
if (SimulatorAddresses.isBounce(d)) {
|
||||
ObjectNode br = bounced.addObject();
|
||||
br.put("emailAddress", d.trim());
|
||||
}
|
||||
}
|
||||
body.put("timestamp", ISO_MILLIS.format(timestamp));
|
||||
body.put("feedbackId", "feedback-" + messageId);
|
||||
}
|
||||
case "COMPLAINT" -> {
|
||||
ArrayNode complained = body.putArray("complainedRecipients");
|
||||
for (String d : destination) {
|
||||
if (SimulatorAddresses.isComplaint(d)) {
|
||||
ObjectNode cr = complained.addObject();
|
||||
cr.put("emailAddress", d.trim());
|
||||
}
|
||||
}
|
||||
body.put("timestamp", ISO_MILLIS.format(timestamp));
|
||||
body.put("feedbackId", "feedback-" + messageId);
|
||||
}
|
||||
case "REJECT" -> body.put("reason", "Bad content");
|
||||
default -> {
|
||||
// SEND and other not-yet-modelled event types: empty block.
|
||||
}
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
private static String eventTypeLabel(String eventType) {
|
||||
return switch (eventType) {
|
||||
case "SEND" -> "Send";
|
||||
case "REJECT" -> "Reject";
|
||||
case "BOUNCE" -> "Bounce";
|
||||
case "COMPLAINT" -> "Complaint";
|
||||
case "DELIVERY" -> "Delivery";
|
||||
case "OPEN" -> "Open";
|
||||
case "CLICK" -> "Click";
|
||||
case "RENDERING_FAILURE" -> "Rendering Failure";
|
||||
case "DELIVERY_DELAY" -> "DeliveryDelay";
|
||||
case "SUBSCRIPTION" -> "Subscription";
|
||||
default -> eventType;
|
||||
};
|
||||
}
|
||||
|
||||
private static String blockName(String eventType) {
|
||||
return switch (eventType) {
|
||||
case "SEND" -> "send";
|
||||
case "REJECT" -> "reject";
|
||||
case "BOUNCE" -> "bounce";
|
||||
case "COMPLAINT" -> "complaint";
|
||||
case "DELIVERY" -> "delivery";
|
||||
case "RENDERING_FAILURE" -> "failure";
|
||||
case "DELIVERY_DELAY" -> "deliveryDelay";
|
||||
default -> eventType.toLowerCase(Locale.ROOT);
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.ses.model.ConfigurationSet;
|
||||
import io.github.hectorvent.floci.services.ses.model.EventDestination;
|
||||
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
|
||||
import io.github.hectorvent.floci.services.ses.model.MessageTag;
|
||||
import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Publishes SES event-publishing notifications to the event destinations attached
|
||||
* to a {@link ConfigurationSet}. This MVP only delivers to {@code SnsDestination};
|
||||
* Firehose, EventBridge, CloudWatch, and Pinpoint destinations are logged and skipped.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class SesEventPublisher {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SesEventPublisher.class);
|
||||
|
||||
private final SnsService snsService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public SesEventPublisher(SnsService snsService, ObjectMapper objectMapper) {
|
||||
this.snsService = snsService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public void publish(ConfigurationSet configurationSet, String eventType, String messageId,
|
||||
String source, String sourceArn, String sendingAccountId,
|
||||
String subject, List<String> toAddresses, List<String> ccAddresses,
|
||||
List<String> bccAddresses, List<String> envelopeDestinations,
|
||||
List<MessageTag> emailTags, List<MessageHeader> additionalHeaders,
|
||||
Instant timestamp, String defaultRegion) {
|
||||
if (configurationSet == null || configurationSet.getEventDestinations().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
ObjectNode payload = SesEventPayload.build(objectMapper, eventType, messageId, source,
|
||||
sourceArn, sendingAccountId, subject,
|
||||
toAddresses, ccAddresses, bccAddresses, envelopeDestinations,
|
||||
configurationSet.getName(), emailTags, additionalHeaders, timestamp);
|
||||
String payloadJson = payload.toString();
|
||||
for (EventDestination ed : configurationSet.getEventDestinations()) {
|
||||
if (!ed.isEnabled()) {
|
||||
continue;
|
||||
}
|
||||
if (ed.getMatchingEventTypes() == null
|
||||
|| !ed.getMatchingEventTypes().contains(eventType)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
dispatch(ed, eventType, payloadJson, defaultRegion);
|
||||
} catch (Exception e) {
|
||||
LOG.warnf(e, "Failed to publish SES event %s to destination %s",
|
||||
eventType, ed.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void dispatch(EventDestination ed, String eventType, String payloadJson, String defaultRegion) {
|
||||
if (ed.getSnsDestination() != null) {
|
||||
String topicArn = ed.getSnsDestination().getTopicArn();
|
||||
if (topicArn == null || topicArn.isBlank()) {
|
||||
LOG.warnf("SES SNS destination %s: event %s not delivered (TopicArn is missing).",
|
||||
ed.getName(), eventType);
|
||||
return;
|
||||
}
|
||||
publishSns(topicArn, payloadJson, defaultRegion);
|
||||
return;
|
||||
}
|
||||
if (ed.getPinpointDestination() != null) {
|
||||
LOG.warnf("SES Pinpoint destination %s: event %s not delivered (Pinpoint service not implemented in Floci).",
|
||||
ed.getName(), eventType);
|
||||
return;
|
||||
}
|
||||
if (ed.getKinesisFirehoseDestination() != null
|
||||
|| ed.getEventBridgeDestination() != null
|
||||
|| ed.getCloudWatchDestination() != null) {
|
||||
LOG.warnf("SES destination %s: event %s not delivered (only SNS publishing is implemented).",
|
||||
ed.getName(), eventType);
|
||||
return;
|
||||
}
|
||||
LOG.warnf("SES destination %s: event %s not delivered (no destination target configured).",
|
||||
ed.getName(), eventType);
|
||||
}
|
||||
|
||||
private void publishSns(String topicArn, String payload, String defaultRegion) {
|
||||
String region = AwsArnUtils.regionOrDefault(topicArn, defaultRegion);
|
||||
try {
|
||||
snsService.publish(topicArn, null, payload, null, region);
|
||||
} catch (AwsException e) {
|
||||
LOG.warnf(e, "SES event publish to SNS topic %s skipped", topicArn);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.ses.model.BulkEmailEntryResult;
|
||||
import io.github.hectorvent.floci.services.ses.model.ConfigurationSet;
|
||||
import io.github.hectorvent.floci.services.ses.model.EmailTemplate;
|
||||
import io.github.hectorvent.floci.services.ses.model.Identity;
|
||||
import io.github.hectorvent.floci.services.ses.model.MessageTag;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -158,9 +159,12 @@ public class SesQueryHandler {
|
||||
String subject = getParam(params, "Message.Subject.Data");
|
||||
String bodyText = getParam(params, "Message.Body.Text.Data");
|
||||
String bodyHtml = getParam(params, "Message.Body.Html.Data");
|
||||
String configurationSetName = getParam(params, "ConfigurationSetName");
|
||||
List<MessageTag> emailTags = extractMessageTags(params, "Tags");
|
||||
|
||||
String messageId = sesService.sendEmail(source, toAddresses, ccAddresses, bccAddresses,
|
||||
replyToAddresses, subject, bodyText, bodyHtml, region);
|
||||
replyToAddresses, subject, bodyText, bodyHtml, configurationSetName,
|
||||
emailTags, List.of(), region);
|
||||
|
||||
String result = new XmlBuilder().elem("MessageId", messageId).build();
|
||||
return Response.ok(AwsQueryResponse.envelope("SendEmail", AwsNamespaces.SES, result)).build();
|
||||
@@ -174,8 +178,11 @@ public class SesQueryHandler {
|
||||
String source = getParam(params, "Source");
|
||||
List<String> destinations = extractMembers(params, "Destinations");
|
||||
String rawMessage = getParam(params, "RawMessage.Data");
|
||||
String configurationSetName = getParam(params, "ConfigurationSetName");
|
||||
List<MessageTag> emailTags = extractMessageTags(params, "Tags");
|
||||
|
||||
String messageId = sesService.sendRawEmail(source, destinations, rawMessage, region);
|
||||
String messageId = sesService.sendRawEmail(source, destinations, rawMessage,
|
||||
configurationSetName, emailTags, region);
|
||||
|
||||
String result = new XmlBuilder().elem("MessageId", messageId).build();
|
||||
return Response.ok(AwsQueryResponse.envelope("SendRawEmail", AwsNamespaces.SES, result)).build();
|
||||
@@ -436,8 +443,11 @@ public class SesQueryHandler {
|
||||
String resolvedName = hasName ? templateName : SesService.templateNameFromArn(templateArn);
|
||||
|
||||
JsonNode templateData = parseTemplateData(templateDataRaw);
|
||||
String configurationSetName = getParam(params, "ConfigurationSetName");
|
||||
List<MessageTag> emailTags = extractMessageTags(params, "Tags");
|
||||
String messageId = sesService.sendTemplatedEmail(source, toAddresses, ccAddresses,
|
||||
bccAddresses, replyToAddresses, resolvedName, templateData, region);
|
||||
bccAddresses, replyToAddresses, resolvedName, templateData,
|
||||
configurationSetName, emailTags, List.of(), region);
|
||||
|
||||
String result = new XmlBuilder().elem("MessageId", messageId).build();
|
||||
return Response.ok(AwsQueryResponse.envelope("SendTemplatedEmail", AwsNamespaces.SES, result)).build();
|
||||
@@ -485,19 +495,25 @@ public class SesQueryHandler {
|
||||
List<String> cc = extractMembers(params, destPrefix + ".Destination.CcAddresses");
|
||||
List<String> bcc = extractMembers(params, destPrefix + ".Destination.BccAddresses");
|
||||
String replacementRaw = getParam(params, destPrefix + ".ReplacementTemplateData");
|
||||
if (to.isEmpty() && cc.isEmpty() && bcc.isEmpty() && replacementRaw == null) {
|
||||
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)));
|
||||
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);
|
||||
}
|
||||
|
||||
String configurationSetName = getParam(params, "ConfigurationSetName");
|
||||
List<MessageTag> defaultEmailTags = extractMessageTags(params, "DefaultTags");
|
||||
List<BulkEmailEntryResult> results = sesService.sendBulkTemplatedEmail(source, replyToAddresses,
|
||||
template.getSubject(), template.getTextPart(), template.getHtmlPart(),
|
||||
defaultTemplateData, entries, region);
|
||||
defaultTemplateData, entries, configurationSetName,
|
||||
defaultEmailTags, List.of(), region);
|
||||
|
||||
XmlBuilder xml = new XmlBuilder().start("Status");
|
||||
for (BulkEmailEntryResult result : results) {
|
||||
@@ -594,6 +610,26 @@ public class SesQueryHandler {
|
||||
return members;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a V1 SES {@code MessageTag} list ({@code <prefix>.member.N.Name} /
|
||||
* {@code .Value}) into a list of {@link MessageTag} records. Returns an empty list when
|
||||
* no members are present.
|
||||
*/
|
||||
private List<MessageTag> extractMessageTags(MultivaluedMap<String, String> params, String prefix) {
|
||||
List<MessageTag> tags = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String name = getParam(params, prefix + ".member." + i + ".Name");
|
||||
String value = getParam(params, prefix + ".member." + i + ".Value");
|
||||
if (name == null && value == null) break;
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"The tag name must be specified.", 400);
|
||||
}
|
||||
tags.add(new MessageTag(name, value));
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
private String getParam(MultivaluedMap<String, String> params, String name) {
|
||||
return params.getFirst(name);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
@@ -11,6 +12,8 @@ import io.github.hectorvent.floci.services.ses.model.ConfigurationSet;
|
||||
import io.github.hectorvent.floci.services.ses.model.EmailTemplate;
|
||||
import io.github.hectorvent.floci.services.ses.model.EventDestination;
|
||||
import io.github.hectorvent.floci.services.ses.model.Identity;
|
||||
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
|
||||
import io.github.hectorvent.floci.services.ses.model.MessageTag;
|
||||
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.Tag;
|
||||
@@ -34,6 +37,7 @@ import java.util.HexFormat;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
@@ -61,9 +65,12 @@ public class SesService {
|
||||
private final StorageBackend<String, AccountSuppressionAttributes> accountSuppressionStore;
|
||||
private final SmtpRelay smtpRelay;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final SesEventPublisher eventPublisher;
|
||||
private final String defaultAccountId;
|
||||
|
||||
@Inject
|
||||
public SesService(StorageFactory storageFactory, SmtpRelay smtpRelay, ObjectMapper objectMapper) {
|
||||
public SesService(StorageFactory storageFactory, SmtpRelay smtpRelay, ObjectMapper objectMapper,
|
||||
SesEventPublisher eventPublisher, EmulatorConfig config) {
|
||||
this.identityStore = storageFactory.create("ses", "ses-identities.json",
|
||||
new TypeReference<Map<String, Identity>>() {});
|
||||
this.emailStore = storageFactory.create("ses", "ses-emails.json",
|
||||
@@ -80,6 +87,8 @@ public class SesService {
|
||||
new TypeReference<Map<String, AccountSuppressionAttributes>>() {});
|
||||
this.smtpRelay = smtpRelay;
|
||||
this.objectMapper = objectMapper;
|
||||
this.eventPublisher = eventPublisher;
|
||||
this.defaultAccountId = config.defaultAccountId();
|
||||
}
|
||||
|
||||
SesService(StorageBackend<String, Identity> identityStore,
|
||||
@@ -100,6 +109,8 @@ public class SesService {
|
||||
this.accountSuppressionStore = accountSuppressionStore;
|
||||
this.smtpRelay = smtpRelay;
|
||||
this.objectMapper = objectMapper;
|
||||
this.eventPublisher = null;
|
||||
this.defaultAccountId = "000000000000";
|
||||
}
|
||||
|
||||
public Identity verifyEmailIdentity(String emailAddress, String region) {
|
||||
@@ -171,7 +182,9 @@ public class SesService {
|
||||
|
||||
public String sendEmail(String source, List<String> toAddresses, List<String> ccAddresses,
|
||||
List<String> bccAddresses, List<String> replyToAddresses,
|
||||
String subject, String bodyText, String bodyHtml, String region) {
|
||||
String subject, String bodyText, String bodyHtml,
|
||||
String configurationSetName, List<MessageTag> emailTags,
|
||||
List<MessageHeader> additionalHeaders, String region) {
|
||||
if (source == null || source.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "Source email is required.", 400);
|
||||
}
|
||||
@@ -181,6 +194,7 @@ public class SesService {
|
||||
if (!hasRecipient) {
|
||||
throw new AwsException("InvalidParameterValue", "At least one destination address is required.", 400);
|
||||
}
|
||||
validateConfigurationSet(configurationSetName, region);
|
||||
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
SentEmail email = new SentEmail(messageId, region, source, toAddresses, ccAddresses,
|
||||
@@ -192,25 +206,138 @@ public class SesService {
|
||||
|
||||
LOG.infov("SES email sent: from={0}, to={1}, subject={2}, messageId={3}",
|
||||
source, toAddresses, subject, messageId);
|
||||
publishSendEvents(configurationSetName, messageId, source, subject,
|
||||
toAddresses, ccAddresses, bccAddresses,
|
||||
allRecipients(toAddresses, ccAddresses, bccAddresses),
|
||||
emailTags, additionalHeaders, region);
|
||||
return messageId;
|
||||
}
|
||||
|
||||
public String sendRawEmail(String source, List<String> destinations, String rawMessage, String region) {
|
||||
public String sendRawEmail(String source, List<String> destinations, String rawMessage,
|
||||
String configurationSetName, List<MessageTag> emailTags,
|
||||
String region) {
|
||||
if (rawMessage == null || rawMessage.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "RawMessage.Data is required.", 400);
|
||||
}
|
||||
validateConfigurationSet(configurationSetName, region);
|
||||
boolean hasExplicitDestinations = destinations != null && !destinations.isEmpty();
|
||||
boolean willPublishEvents = configurationSetName != null && !configurationSetName.isBlank();
|
||||
SmtpRelay.RawMessageHeaders headers = (hasExplicitDestinations && !willPublishEvents)
|
||||
? null
|
||||
: SmtpRelay.parseRawHeaders(rawMessage);
|
||||
List<String> effectiveDestinations = hasExplicitDestinations
|
||||
? destinations
|
||||
: allRecipients(headers.to(), headers.cc(), headers.bcc());
|
||||
if (effectiveDestinations.isEmpty()) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"At least one destination address is required.", 400);
|
||||
}
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
SentEmail email = new SentEmail(messageId, region, source,
|
||||
destinations != null ? destinations : Collections.emptyList(),
|
||||
rawMessage);
|
||||
SentEmail email = new SentEmail(messageId, region, source, effectiveDestinations, rawMessage);
|
||||
emailStore.put("email::" + region + "::" + messageId, email);
|
||||
|
||||
smtpRelay.relayRaw(source, destinations, rawMessage);
|
||||
smtpRelay.relayRaw(source, effectiveDestinations, rawMessage);
|
||||
|
||||
LOG.infov("SES raw email sent: from={0}, messageId={1}", source, messageId);
|
||||
publishSendEvents(configurationSetName, messageId, source,
|
||||
headers != null ? headers.subject() : "",
|
||||
headers != null ? headers.to() : List.of(),
|
||||
headers != null ? headers.cc() : List.of(),
|
||||
headers != null ? headers.bcc() : List.of(),
|
||||
effectiveDestinations,
|
||||
emailTags, List.of(), region);
|
||||
return messageId;
|
||||
}
|
||||
|
||||
private static List<String> allRecipients(List<String> to, List<String> cc, List<String> bcc) {
|
||||
List<String> all = new ArrayList<>();
|
||||
if (to != null) {
|
||||
all.addAll(to);
|
||||
}
|
||||
if (cc != null) {
|
||||
all.addAll(cc);
|
||||
}
|
||||
if (bcc != null) {
|
||||
all.addAll(bcc);
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that a non-blank {@code ConfigurationSetName} refers to a configuration set
|
||||
* that exists in the given region. Always raises {@code ConfigurationSetDoesNotExist}
|
||||
* with {@code httpStatus = 400}; the V2 REST controller's {@code remapV1Exception}
|
||||
* then translates that into a {@code NotFoundException 404}, while V1 Query keeps the
|
||||
* original code/status. Mirrors AWS SES behaviour: invalid set name fails fast instead
|
||||
* of silently storing/relaying the message and skipping event publishing later.
|
||||
*/
|
||||
private void validateConfigurationSet(String configurationSetName, String region) {
|
||||
if (configurationSetName == null || configurationSetName.isBlank()) {
|
||||
return;
|
||||
}
|
||||
if (configSetStore.get(configSetKey(region, configurationSetName)).isEmpty()) {
|
||||
throw new AwsException("ConfigurationSetDoesNotExist",
|
||||
"Configuration set <" + configurationSetName + "> does not exist.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private void publishSendEvents(String configurationSetName, String messageId, String source,
|
||||
String subject, List<String> toAddresses,
|
||||
List<String> ccAddresses, List<String> bccAddresses,
|
||||
List<String> envelopeDestinations,
|
||||
List<MessageTag> emailTags,
|
||||
List<MessageHeader> additionalHeaders, String region) {
|
||||
if (eventPublisher == null) {
|
||||
return;
|
||||
}
|
||||
if (configurationSetName == null || configurationSetName.isBlank() || messageId == null) {
|
||||
return;
|
||||
}
|
||||
ConfigurationSet cs = configSetStore.get(configSetKey(region, configurationSetName)).orElse(null);
|
||||
if (cs == null) {
|
||||
LOG.warnv("SES send references unknown ConfigurationSet <{0}>; events not published.",
|
||||
configurationSetName);
|
||||
return;
|
||||
}
|
||||
if (cs.getEventDestinations().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<String> envelope = envelopeDestinations != null
|
||||
? envelopeDestinations : Collections.emptyList();
|
||||
Instant timestamp = Instant.now();
|
||||
String sendingAccountId = defaultAccountId;
|
||||
String sourceArn = (source == null || source.isBlank())
|
||||
? null
|
||||
: AwsArnUtils.Arn.of("ses", region, sendingAccountId, "identity/" + source).toString();
|
||||
|
||||
for (String eventType : determineSendEventTypes(envelope)) {
|
||||
eventPublisher.publish(cs, eventType, messageId, source, sourceArn, sendingAccountId,
|
||||
subject, toAddresses, ccAddresses, bccAddresses, envelope,
|
||||
emailTags, additionalHeaders, timestamp, region);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> determineSendEventTypes(List<String> destinations) {
|
||||
List<String> events = new ArrayList<>();
|
||||
events.add("SEND");
|
||||
for (String d : destinations) {
|
||||
if (SimulatorAddresses.isSuccess(d) && !events.contains("DELIVERY")) {
|
||||
events.add("DELIVERY");
|
||||
}
|
||||
if (SimulatorAddresses.isBounce(d) && !events.contains("BOUNCE")) {
|
||||
events.add("BOUNCE");
|
||||
}
|
||||
if (SimulatorAddresses.isComplaint(d) && !events.contains("COMPLAINT")) {
|
||||
events.add("COMPLAINT");
|
||||
}
|
||||
if (SimulatorAddresses.isSuppressionList(d) && !events.contains("REJECT")) {
|
||||
events.add("REJECT");
|
||||
}
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
public long getSentEmailCount(String region) {
|
||||
String prefix = "email::" + region + "::";
|
||||
return emailStore.scan(k -> k.startsWith(prefix)).size();
|
||||
@@ -981,11 +1108,14 @@ public class SesService {
|
||||
|
||||
public String sendTemplatedEmail(String source, List<String> toAddresses, List<String> ccAddresses,
|
||||
List<String> bccAddresses, List<String> replyToAddresses,
|
||||
String templateName, JsonNode templateData, String region) {
|
||||
String templateName, JsonNode templateData,
|
||||
String configurationSetName, List<MessageTag> emailTags,
|
||||
List<MessageHeader> additionalHeaders, String region) {
|
||||
EmailTemplate template = getTemplate(templateName, region);
|
||||
return sendInlineTemplatedEmail(source, toAddresses, ccAddresses, bccAddresses,
|
||||
replyToAddresses, template.getSubject(), template.getTextPart(),
|
||||
template.getHtmlPart(), templateData, region);
|
||||
template.getHtmlPart(), templateData,
|
||||
configurationSetName, emailTags, additionalHeaders, region);
|
||||
}
|
||||
|
||||
public String renderTestTemplate(String templateName, String templateDataRaw, String region) {
|
||||
@@ -1104,7 +1234,10 @@ public class SesService {
|
||||
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 region) {
|
||||
JsonNode templateData,
|
||||
String configurationSetName, List<MessageTag> emailTags,
|
||||
List<MessageHeader> additionalHeaders,
|
||||
String region) {
|
||||
boolean hasSubject = subject != null && !subject.isBlank();
|
||||
boolean hasText = textPart != null && !textPart.isBlank();
|
||||
boolean hasHtml = htmlPart != null && !htmlPart.isBlank();
|
||||
@@ -1116,7 +1249,7 @@ public class SesService {
|
||||
applyTemplateData(subject, templateData),
|
||||
applyTemplateData(textPart, templateData),
|
||||
applyTemplateData(htmlPart, templateData),
|
||||
region);
|
||||
configurationSetName, emailTags, additionalHeaders, region);
|
||||
}
|
||||
|
||||
public List<BulkEmailEntryResult> sendBulkTemplatedEmail(String source,
|
||||
@@ -1124,6 +1257,9 @@ public class SesService {
|
||||
String subject, String textPart, String htmlPart,
|
||||
JsonNode defaultTemplateData,
|
||||
List<BulkEmailEntry> entries,
|
||||
String configurationSetName,
|
||||
List<MessageTag> defaultEmailTags,
|
||||
List<MessageHeader> defaultHeaders,
|
||||
String region) {
|
||||
if (source == null || source.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "Source email is required.", 400);
|
||||
@@ -1139,6 +1275,7 @@ public class SesService {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"At least one destination entry is required.", 400);
|
||||
}
|
||||
validateConfigurationSet(configurationSetName, region);
|
||||
if (entries.size() > MAX_BULK_DESTINATIONS) {
|
||||
throw new AwsException("MessageRejected",
|
||||
"Number of destinations (" + entries.size() + ") exceeds the maximum of "
|
||||
@@ -1159,13 +1296,15 @@ public class SesService {
|
||||
for (BulkEmailEntry entry : entries) {
|
||||
try {
|
||||
JsonNode merged = mergeTemplateData(defaultTemplateData, entry.replacementTemplateData());
|
||||
List<MessageTag> mergedTags = mergeEmailTags(defaultEmailTags, entry.replacementEmailTags());
|
||||
List<MessageHeader> mergedHeaders = mergeHeaders(defaultHeaders, entry.replacementHeaders());
|
||||
String messageId = sendEmail(source,
|
||||
entry.toAddresses(), entry.ccAddresses(), entry.bccAddresses(),
|
||||
replyToAddresses,
|
||||
applyTemplateData(subject, merged),
|
||||
applyTemplateData(textPart, merged),
|
||||
applyTemplateData(htmlPart, merged),
|
||||
region);
|
||||
configurationSetName, mergedTags, mergedHeaders, region);
|
||||
results.add(BulkEmailEntryResult.success(messageId));
|
||||
} catch (AwsException e) {
|
||||
results.add(BulkEmailEntryResult.failure(
|
||||
@@ -1190,6 +1329,57 @@ public class SesService {
|
||||
return BulkEmailEntryResult.Status.FAILED;
|
||||
}
|
||||
|
||||
static List<MessageHeader> mergeHeaders(List<MessageHeader> defaults, List<MessageHeader> replacement) {
|
||||
boolean hasDefault = defaults != null && !defaults.isEmpty();
|
||||
boolean hasReplacement = replacement != null && !replacement.isEmpty();
|
||||
if (!hasDefault && !hasReplacement) {
|
||||
return List.of();
|
||||
}
|
||||
// RFC 5322 header field names are case-insensitive, so the merge key is the
|
||||
// lowercased name. The header itself is stored verbatim, so the replacement's
|
||||
// original casing wins when it overrides a default.
|
||||
LinkedHashMap<String, MessageHeader> byLowerName = new LinkedHashMap<>();
|
||||
if (hasDefault) {
|
||||
for (MessageHeader h : defaults) {
|
||||
if (h != null && h.name() != null && !h.name().isBlank()) {
|
||||
byLowerName.put(h.name().toLowerCase(Locale.ROOT), h);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (hasReplacement) {
|
||||
for (MessageHeader h : replacement) {
|
||||
if (h != null && h.name() != null && !h.name().isBlank()) {
|
||||
byLowerName.put(h.name().toLowerCase(Locale.ROOT), h);
|
||||
}
|
||||
}
|
||||
}
|
||||
return new ArrayList<>(byLowerName.values());
|
||||
}
|
||||
|
||||
static List<MessageTag> mergeEmailTags(List<MessageTag> defaults, List<MessageTag> replacement) {
|
||||
boolean hasDefault = defaults != null && !defaults.isEmpty();
|
||||
boolean hasReplacement = replacement != null && !replacement.isEmpty();
|
||||
if (!hasDefault && !hasReplacement) {
|
||||
return List.of();
|
||||
}
|
||||
LinkedHashMap<String, MessageTag> byName = new LinkedHashMap<>();
|
||||
if (hasDefault) {
|
||||
for (MessageTag t : defaults) {
|
||||
if (t != null && t.name() != null && !t.name().isBlank()) {
|
||||
byName.put(t.name(), t);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (hasReplacement) {
|
||||
for (MessageTag t : replacement) {
|
||||
if (t != null && t.name() != null && !t.name().isBlank()) {
|
||||
byName.put(t.name(), t);
|
||||
}
|
||||
}
|
||||
}
|
||||
return new ArrayList<>(byName.values());
|
||||
}
|
||||
|
||||
static JsonNode mergeTemplateData(JsonNode defaults, JsonNode replacement) {
|
||||
boolean hasDefault = defaults != null && defaults.isObject();
|
||||
boolean hasReplacement = replacement != null && replacement.isObject();
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
/**
|
||||
* Recognises the AWS Amazon SES mailbox simulator addresses
|
||||
* (see https://docs.aws.amazon.com/ses/latest/dg/send-an-email-from-console.html#send-email-simulator)
|
||||
* so Floci can deterministically emit the matching event types.
|
||||
*/
|
||||
final class SimulatorAddresses {
|
||||
|
||||
static final String SUCCESS = "success@simulator.amazonses.com";
|
||||
static final String BOUNCE = "bounce@simulator.amazonses.com";
|
||||
static final String COMPLAINT = "complaint@simulator.amazonses.com";
|
||||
static final String SUPPRESSION_LIST = "suppressionlist@simulator.amazonses.com";
|
||||
|
||||
private SimulatorAddresses() {}
|
||||
|
||||
static boolean isSuccess(String address) {
|
||||
return SUCCESS.equalsIgnoreCase(strip(address));
|
||||
}
|
||||
|
||||
static boolean isBounce(String address) {
|
||||
return BOUNCE.equalsIgnoreCase(strip(address));
|
||||
}
|
||||
|
||||
static boolean isComplaint(String address) {
|
||||
return COMPLAINT.equalsIgnoreCase(strip(address));
|
||||
}
|
||||
|
||||
static boolean isSuppressionList(String address) {
|
||||
return SUPPRESSION_LIST.equalsIgnoreCase(strip(address));
|
||||
}
|
||||
|
||||
private static String strip(String address) {
|
||||
return address == null ? null : address.trim();
|
||||
}
|
||||
}
|
||||
@@ -278,6 +278,56 @@ public class SmtpRelay {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Structured headers extracted from a raw RFC 5322 MIME message:
|
||||
* subject and separate To / Cc / Bcc address lists. Empty fields when the
|
||||
* corresponding header is missing.
|
||||
*/
|
||||
public record RawMessageHeaders(String subject, List<String> to, List<String> cc, List<String> bcc) {
|
||||
public static RawMessageHeaders empty() {
|
||||
return new RawMessageHeaders("", List.of(), List.of(), List.of());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a raw RFC 5322 MIME message (plain or base64-encoded) into
|
||||
* {@link RawMessageHeaders}. Returns an empty result when the input is blank
|
||||
* or unparseable.
|
||||
*/
|
||||
public static RawMessageHeaders parseRawHeaders(String rawMessage) {
|
||||
if (rawMessage == null || rawMessage.isBlank()) {
|
||||
return RawMessageHeaders.empty();
|
||||
}
|
||||
try {
|
||||
byte[] mimeBytes = tryBase64Decode(rawMessage);
|
||||
var builder = new DefaultMessageBuilder();
|
||||
var message = builder.parseMessage(new ByteArrayInputStream(mimeBytes));
|
||||
String subject = message.getSubject() != null ? message.getSubject() : "";
|
||||
List<String> to = message.getTo() != null
|
||||
? toMailboxAddresses(message.getTo().flatten()) : List.of();
|
||||
List<String> cc = message.getCc() != null
|
||||
? toMailboxAddresses(message.getCc().flatten()) : List.of();
|
||||
List<String> bcc = message.getBcc() != null
|
||||
? toMailboxAddresses(message.getBcc().flatten()) : List.of();
|
||||
return new RawMessageHeaders(subject, to, cc, bcc);
|
||||
} catch (Exception e) {
|
||||
return RawMessageHeaders.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the flat list of recipients (To + Cc + Bcc) parsed from a raw RFC 5322
|
||||
* MIME message. Convenience wrapper around {@link #parseRawHeaders}.
|
||||
*/
|
||||
public static List<String> parseRawRecipients(String rawMessage) {
|
||||
RawMessageHeaders h = parseRawHeaders(rawMessage);
|
||||
List<String> all = new ArrayList<>();
|
||||
all.addAll(h.to());
|
||||
all.addAll(h.cc());
|
||||
all.addAll(h.bcc());
|
||||
return all;
|
||||
}
|
||||
|
||||
private static List<String> toMailboxAddresses(MailboxList list) {
|
||||
List<String> addresses = new ArrayList<>();
|
||||
for (Mailbox mailbox : list) {
|
||||
|
||||
@@ -10,5 +10,7 @@ public record BulkEmailEntry(
|
||||
List<String> toAddresses,
|
||||
List<String> ccAddresses,
|
||||
List<String> bccAddresses,
|
||||
JsonNode replacementTemplateData
|
||||
JsonNode replacementTemplateData,
|
||||
List<MessageTag> replacementEmailTags,
|
||||
List<MessageHeader> replacementHeaders
|
||||
) {}
|
||||
@@ -0,0 +1,15 @@
|
||||
package io.github.hectorvent.floci.services.ses.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/**
|
||||
* Represents one entry of the SES V2 {@code Content.Simple.Headers} /
|
||||
* {@code Content.Template.Headers} list — a user-supplied additional header to attach to
|
||||
* an outgoing message.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public record MessageHeader(
|
||||
@JsonProperty("Name") String name,
|
||||
@JsonProperty("Value") String value) {
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package io.github.hectorvent.floci.services.ses.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/**
|
||||
* Represents one entry of an AWS SES {@code EmailTags} / {@code DefaultEmailTags} /
|
||||
* {@code ReplacementTags} list — also known as a {@code MessageTag} in the SES API.
|
||||
* Used to attach name/value pairs to a single sent message for analytics and event
|
||||
* publishing (the values surface in {@code mail.tags} on published events).
|
||||
*
|
||||
* <p>Distinct from {@link Tag}, which models the resource tags applied to a
|
||||
* {@code ConfigurationSet} / {@code EmailTemplate} / {@code Identity} via the
|
||||
* {@code TagResource} / {@code UntagResource} APIs — those use {@code Key}/{@code Value},
|
||||
* not {@code Name}/{@code Value}.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public record MessageTag(
|
||||
@JsonProperty("Name") String name,
|
||||
@JsonProperty("Value") String value) {
|
||||
}
|
||||
Reference in new issue
Block a user