diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java index a9c9cf95f4..5427272523 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java @@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.cognito.verification; import io.github.hectorvent.floci.services.cognito.model.CognitoUser; import io.github.hectorvent.floci.services.cognito.model.UserPool; import io.github.hectorvent.floci.services.ses.SesService; +import io.github.hectorvent.floci.services.ses.model.EmailContent; +import io.github.hectorvent.floci.services.ses.model.SendEmailRequest; import io.github.hectorvent.floci.services.sns.SnsService; import java.util.List; @@ -67,21 +69,12 @@ public final class CognitoMessageDispatcher { String rawBody = stringOrNull(customMessageResponse, "emailMessage"); if (rawBody == null) rawBody = stringOr(template.get(emailTemplateKey()), DEFAULT_EMAIL_BODY); String body = renderTemplate(rawBody, code); - ses.sendEmail( - DEFAULT_FROM, - List.of(email), - List.of(), List.of(), List.of(), - null, // returnPath - subject, - body, - null, // bodyHtml - null, // configurationSetName - List.of(), // emailTags - List.of(), // additionalHeaders - null, // listManagement - null, // tenantName - DEFAULT_REGION - ); + ses.sendEmail(SendEmailRequest.builder() + .source(DEFAULT_FROM) + .toAddresses(List.of(email)) + .region(DEFAULT_REGION) + .content(new EmailContent.Simple(subject, body, null, List.of())) + .build()); } else if ("SMS".equalsIgnoreCase(medium) && phone != null) { String rawBody = stringOrNull(customMessageResponse, "smsMessage"); if (rawBody == null) rawBody = stringOr(resolveSmsTemplate(pool, template, purpose), DEFAULT_SMS_BODY); diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java index 6deb2f4666..f5d2c175f4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java @@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.ses.model.CloudWatchDimensionConfigur import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; import io.github.hectorvent.floci.services.ses.model.CustomVerificationEmailTemplate; import io.github.hectorvent.floci.services.ses.model.DeliveryOptions; +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.EventDestination; import io.github.hectorvent.floci.services.ses.model.Identity; @@ -21,6 +22,8 @@ import io.github.hectorvent.floci.services.ses.model.ReceiptAction; import io.github.hectorvent.floci.services.ses.model.ReceiptFilter; import io.github.hectorvent.floci.services.ses.model.ReceiptRule; import io.github.hectorvent.floci.services.ses.model.ReceiptRuleSet; +import io.github.hectorvent.floci.services.ses.model.SendBulkEmailRequest; +import io.github.hectorvent.floci.services.ses.model.SendEmailRequest; import io.github.hectorvent.floci.services.ses.model.SnsDestination; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; @@ -253,9 +256,18 @@ public class SesQueryHandler { List emailTags = extractMessageTags(params, "Tags"); // ListManagementOptions is a v2-only SendEmail field; the v1 Query API has no equivalent. - String messageId = sesService.sendEmail(source, toAddresses, ccAddresses, bccAddresses, - replyToAddresses, returnPath, subject, bodyText, bodyHtml, configurationSetName, - emailTags, List.of(), null, null, region); + String messageId = sesService.sendEmail(SendEmailRequest.builder() + .source(source) + .toAddresses(toAddresses) + .ccAddresses(ccAddresses) + .bccAddresses(bccAddresses) + .replyToAddresses(replyToAddresses) + .returnPath(returnPath) + .configurationSetName(configurationSetName) + .emailTags(emailTags) + .region(region) + .content(new EmailContent.Simple(subject, bodyText, bodyHtml, List.of())) + .build()); String result = new XmlBuilder().elem("MessageId", messageId).build(); return Response.ok(AwsQueryResponse.envelope("SendEmail", AwsNamespaces.SES, result)).build(); @@ -272,8 +284,14 @@ public class SesQueryHandler { String configurationSetName = getParam(params, "ConfigurationSetName"); List emailTags = extractMessageTags(params, "Tags"); - String messageId = sesService.sendRawEmail(source, destinations, rawMessage, - null, configurationSetName, emailTags, null, null, region); + String messageId = sesService.sendEmail(SendEmailRequest.builder() + .source(source) + .toAddresses(destinations) + .configurationSetName(configurationSetName) + .emailTags(emailTags) + .region(region) + .content(new EmailContent.Raw(rawMessage)) + .build()); String result = new XmlBuilder().elem("MessageId", messageId).build(); return Response.ok(AwsQueryResponse.envelope("SendRawEmail", AwsNamespaces.SES, result)).build(); @@ -609,9 +627,18 @@ public class SesQueryHandler { String configurationSetName = getParam(params, "ConfigurationSetName"); String returnPath = getParam(params, "ReturnPath"); List emailTags = extractMessageTags(params, "Tags"); - String messageId = sesService.sendTemplatedEmail(source, toAddresses, ccAddresses, - bccAddresses, replyToAddresses, returnPath, resolvedName, templateData, - configurationSetName, emailTags, List.of(), null, null, region); + String messageId = sesService.sendEmail(SendEmailRequest.builder() + .source(source) + .toAddresses(toAddresses) + .ccAddresses(ccAddresses) + .bccAddresses(bccAddresses) + .replyToAddresses(replyToAddresses) + .returnPath(returnPath) + .configurationSetName(configurationSetName) + .emailTags(emailTags) + .region(region) + .content(new EmailContent.Template(resolvedName, templateData, List.of())) + .build()); String result = new XmlBuilder().elem("MessageId", messageId).build(); return Response.ok(AwsQueryResponse.envelope("SendTemplatedEmail", AwsNamespaces.SES, result)).build(); @@ -755,10 +782,17 @@ public class SesQueryHandler { String configurationSetName = getParam(params, "ConfigurationSetName"); String returnPath = getParam(params, "ReturnPath"); List defaultEmailTags = extractMessageTags(params, "DefaultTags"); - List results = sesService.sendBulkTemplatedEmail(source, replyToAddresses, - returnPath, template.getSubject(), template.getTextPart(), template.getHtmlPart(), - defaultTemplateData, entries, configurationSetName, - defaultEmailTags, List.of(), null, region); + List results = sesService.sendBulkEmail(SendBulkEmailRequest.builder() + .source(source) + .replyToAddresses(replyToAddresses) + .returnPath(returnPath) + .configurationSetName(configurationSetName) + .defaultEmailTags(defaultEmailTags) + .region(region) + .defaultContent(new EmailContent.InlineTemplate(template.getSubject(), template.getTextPart(), + template.getHtmlPart(), defaultTemplateData, List.of())) + .entries(entries) + .build()); XmlBuilder xml = new XmlBuilder().start("Status"); for (BulkEmailEntryResult result : results) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesSendController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesSendController.java index dc0704ad29..9d17e11d78 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesSendController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesSendController.java @@ -9,10 +9,13 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; 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.MessageHeader; import io.github.hectorvent.floci.services.ses.model.MessageTag; +import io.github.hectorvent.floci.services.ses.model.SendBulkEmailRequest; +import io.github.hectorvent.floci.services.ses.model.SendEmailRequest; import io.github.hectorvent.floci.services.ses.model.Tag; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; @@ -101,13 +104,24 @@ public class SesSendController { List replyToAddresses = jsonArrayToList(request.path("ReplyToAddresses")); String feedbackForwardingAddress = request.path("FeedbackForwardingEmailAddress").asText(null); - List allDestinations = mergeLists(toAddresses, ccAddresses, bccAddresses); String configurationSetName = request.path("ConfigurationSetName").asText(null); String tenantName = stringMemberOrAbsent(request, "TenantName"); List emailTags = parseEmailTagsArray(request.path("EmailTags"), "EmailTags"); ListManagementOptions listManagement = parseListManagementOptions(request.path("ListManagementOptions")); + SendEmailRequest.Builder sendRequest = SendEmailRequest.builder() + .source(fromEmailAddress) + .toAddresses(toAddresses) + .ccAddresses(ccAddresses) + .bccAddresses(bccAddresses) + .replyToAddresses(replyToAddresses) + .returnPath(feedbackForwardingAddress) + .configurationSetName(configurationSetName) + .emailTags(emailTags) + .listManagement(listManagement) + .tenantName(tenantName) + .region(region); JsonNode content = request.path("Content"); String messageId; @@ -117,15 +131,13 @@ public class SesSendController { throw new AwsException("BadRequestException", "Content.Raw.Data is required.", 400); } - if (allDestinations.isEmpty()) { + if (toAddresses.isEmpty() && ccAddresses.isEmpty() && bccAddresses.isEmpty()) { throw new AwsException("BadRequestException", "At least one destination address is required.", 400); } sesService.checkTenantRawSendAccess(tenantName, fromEmailAddress, rawData, configurationSetName, regionResolver.getAccountId(), region); - messageId = sesService.sendRawEmail(fromEmailAddress, allDestinations, rawData, - feedbackForwardingAddress, configurationSetName, emailTags, listManagement, - tenantName, region); + messageId = sesService.sendEmail(sendRequest.content(new EmailContent.Raw(rawData)).build()); } else if (content.has("Simple")) { if (fromEmailAddress == null || fromEmailAddress.isBlank()) { // AWS returns BadRequestException with a null message body here. @@ -139,11 +151,9 @@ public class SesSendController { parseHeadersArray(simple.path("Headers"), "content.simple.headers"); sesService.checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName, null, regionResolver.getAccountId(), region); - messageId = sesService.sendEmail(fromEmailAddress, toAddresses, ccAddresses, - bccAddresses, replyToAddresses, feedbackForwardingAddress, - subject, bodyText, bodyHtml, - configurationSetName, emailTags, additionalHeaders, listManagement, - tenantName, region); + messageId = sesService.sendEmail(sendRequest + .content(new EmailContent.Simple(subject, bodyText, bodyHtml, additionalHeaders)) + .build()); } else if (content.has("Template")) { if (fromEmailAddress == null || fromEmailAddress.isBlank()) { throw new AwsException("BadRequestException", "Source cannot be empty", 400); @@ -173,10 +183,9 @@ public class SesSendController { : SesTemplateService.templateNameFromArn(templateArn); sesService.checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName, resolvedName, regionResolver.getAccountId(), region); - messageId = sesService.sendTemplatedEmail(fromEmailAddress, toAddresses, ccAddresses, - bccAddresses, replyToAddresses, feedbackForwardingAddress, - resolvedName, templateData, - configurationSetName, emailTags, additionalHeaders, listManagement, tenantName, region); + messageId = sesService.sendEmail(sendRequest + .content(new EmailContent.Template(resolvedName, templateData, additionalHeaders)) + .build()); } else { JsonNode inline = template.path("TemplateContent"); String subject = inline.path("Subject").asText(null); @@ -188,10 +197,10 @@ public class SesSendController { SesService.requireInlineTemplateContent(subject, text, html); sesService.checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName, null, regionResolver.getAccountId(), region); - messageId = sesService.sendInlineTemplatedEmail(fromEmailAddress, toAddresses, - ccAddresses, bccAddresses, replyToAddresses, feedbackForwardingAddress, - subject, text, html, templateData, - configurationSetName, emailTags, additionalHeaders, listManagement, tenantName, region); + messageId = sesService.sendEmail(sendRequest + .content(new EmailContent.InlineTemplate(subject, text, html, templateData, + additionalHeaders)) + .build()); } } else { throw new AwsException("BadRequestException", @@ -316,10 +325,18 @@ public class SesSendController { sesService.checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName, gateTemplateName, regionResolver.getAccountId(), region); - List results = sesService.sendBulkTemplatedEmail(fromEmailAddress, - replyToAddresses, feedbackForwardingAddress, subject, text, html, - defaultTemplateData, entries, configurationSetName, - defaultEmailTags, defaultHeaders, tenantName, region); + List results = sesService.sendBulkEmail(SendBulkEmailRequest.builder() + .source(fromEmailAddress) + .replyToAddresses(replyToAddresses) + .returnPath(feedbackForwardingAddress) + .configurationSetName(configurationSetName) + .defaultEmailTags(defaultEmailTags) + .tenantName(tenantName) + .region(region) + .defaultContent(new EmailContent.InlineTemplate(subject, text, html, defaultTemplateData, + defaultHeaders)) + .entries(entries) + .build()); ObjectNode response = objectMapper.createObjectNode(); ArrayNode arr = response.putArray("BulkEmailEntryResults"); @@ -390,13 +407,6 @@ public class SesSendController { return list; } - private List mergeLists(List to, List cc, List bcc) { - List all = new ArrayList<>(to); - all.addAll(cc); - all.addAll(bcc); - return all; - } - private JsonNode parseTemplateData(JsonNode parent, String fieldName) { if (parent == null || parent.isMissingNode() || parent.isNull()) { return objectMapper.createObjectNode(); diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java index 97c671c667..4ed0d90d57 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java @@ -11,11 +11,13 @@ import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; import io.github.hectorvent.floci.services.ses.model.Contact; import io.github.hectorvent.floci.services.ses.model.CustomVerificationEmailTemplate; import io.github.hectorvent.floci.services.ses.model.DeliveryOptions; -import io.github.hectorvent.floci.services.ses.model.EmailTemplate; +import io.github.hectorvent.floci.services.ses.model.EmailContent; import io.github.hectorvent.floci.services.ses.model.Identity; import io.github.hectorvent.floci.services.ses.model.ListManagementOptions; 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.SendBulkEmailRequest; +import io.github.hectorvent.floci.services.ses.model.SendEmailRequest; import io.github.hectorvent.floci.services.ses.model.Topic; import io.github.hectorvent.floci.services.ses.model.TrackingOptions; import io.github.hectorvent.floci.services.ses.model.SentEmail; @@ -212,67 +214,82 @@ public class SesService { LOG.infov("Deleted identity: {0}", identityValue); } - public String sendEmail(String source, List toAddresses, List ccAddresses, - List bccAddresses, List replyToAddresses, String returnPath, - String subject, String bodyText, String bodyHtml, - String configurationSetName, List emailTags, - List additionalHeaders, ListManagementOptions listManagement, - String tenantName, String region) { + public String sendEmail(SendEmailRequest request) { + return switch (request.content()) { + case EmailContent.Simple simple -> sendSimpleEmail(request, simple); + case EmailContent.Template template -> + sendInlineTemplatedEmail(request, templateService.inline(template, request.region())); + case EmailContent.InlineTemplate inline -> sendInlineTemplatedEmail(request, inline); + case EmailContent.Raw raw -> sendRawEmail(request, raw); + }; + } + + private String sendInlineTemplatedEmail(SendEmailRequest request, EmailContent.InlineTemplate template) { + requireInlineTemplateContent(template.subject(), template.textPart(), template.htmlPart()); + EmailContent.Simple rendered = SesTemplateService.render(template); + return sendSimpleEmail(request.toBuilder().content(rendered).build(), rendered); + } + + private String sendSimpleEmail(SendEmailRequest request, EmailContent.Simple content) { + String source = request.source(); + String region = request.region(); if (source == null || source.isBlank()) { throw new AwsException("InvalidParameterValue", "Source email is required.", 400); } - boolean hasRecipient = (toAddresses != null && !toAddresses.isEmpty()) - || (ccAddresses != null && !ccAddresses.isEmpty()) - || (bccAddresses != null && !bccAddresses.isEmpty()); - if (!hasRecipient) { + if (!request.hasRecipients()) { throw new AwsException("InvalidParameterValue", "At least one destination address is required.", 400); } - String effectiveConfigSet = resolveDefaultConfigurationSet(configurationSetName, source, region); + String effectiveConfigSet = resolveDefaultConfigurationSet(request.configurationSetName(), source, region); configSetService.validateForSending(effectiveConfigSet, 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. - List envelope = allRecipients(toAddresses, ccAddresses, bccAddresses); + List envelope = request.recipients(); Map suppressedReasons = new LinkedHashMap<>( collectSuppressedReasons(envelope, effectiveConfigSet, region)); // putIfAbsent so a suppression-list reason already set for an address (e.g. COMPLAINT) wins // over the list-management opt-out and keeps its synthetic event type. - contactService.collectListManagementOptOuts(envelope, listManagement, region, + contactService.collectListManagementOptOuts(envelope, request.listManagement(), region, SesService::extractEmailAddress).forEach(suppressedReasons::putIfAbsent); // A single-recipient list-managed send gets a functional unsubscribe link: the // {{amazonSESUnsubscribeUrl}} body placeholder is replaced and the List-Unsubscribe headers // are added, matching AWS (which only injects these for a single recipient). The link // resolves to Floci's own /_aws/ses/unsubscribe endpoint. - if (hasListManagement(listManagement) && envelope.size() == 1) { - String url = buildUnsubscribeUrl(region, listManagement, extractEmailAddress(envelope.get(0))); - bodyText = replaceUnsubscribePlaceholder(bodyText, url); - bodyHtml = replaceUnsubscribePlaceholder(bodyHtml, url); - additionalHeaders = withUnsubscribeHeaders(additionalHeaders, url); + if (hasListManagement(request.listManagement()) && envelope.size() == 1) { + String url = buildUnsubscribeUrl(region, request.listManagement(), extractEmailAddress(envelope.get(0))); + content = new EmailContent.Simple(content.subject(), + replaceUnsubscribePlaceholder(content.bodyText(), url), + replaceUnsubscribePlaceholder(content.bodyHtml(), url), + withUnsubscribeHeaders(content.headers(), url)); + request = request.toBuilder().content(content).build(); } // Drop unsafe user-supplied headers (blank name or CR/LF in name/value) once here, so the // stored SentEmail, the SMTP relay, and the published events all reflect the same sanitized // set and no injection payload is retained on any surface. - if (additionalHeaders != null) { - additionalHeaders = additionalHeaders.stream().filter(MessageHeader::isSafe).toList(); + if (content.hasHeaders()) { + content = content.withSafeHeaders(); + request = request.toBuilder().content(content).build(); } String messageId = UUID.randomUUID().toString(); - String effectiveReturnPath = firstNonBlank(returnPath, source); + String effectiveReturnPath = firstNonBlank(request.returnPath(), source); // SES accepts the message and then rejects it as a whole when the content scan trips, so // the send still succeeds and a REJECT event is published in place of any delivery. - boolean rejected = SesContentScan.containsTestVirus(subject, bodyText, bodyHtml) - || SesContentScan.containsTestVirus(headerText(additionalHeaders)); - SentEmail email = new SentEmail(messageId, region, source, toAddresses, ccAddresses, - bccAddresses, replyToAddresses, subject, bodyText, bodyHtml); + boolean rejected = SesContentScan.containsTestVirus(content.subject(), content.bodyText(), + content.bodyHtml()) + || SesContentScan.containsTestVirus(headerText(content.headers())); + SentEmail email = new SentEmail(messageId, region, source, request.toAddresses(), + request.ccAddresses(), request.bccAddresses(), request.replyToAddresses(), content.subject(), + content.bodyText(), content.bodyHtml()); email.setReturnPath(effectiveReturnPath); email.setConfigurationSetName(firstNonBlank(effectiveConfigSet)); - email.setTenantName(firstNonBlank(tenantName)); - if (additionalHeaders != null && !additionalHeaders.isEmpty()) { - email.setHeaders(additionalHeaders); + email.setTenantName(firstNonBlank(request.tenantName())); + if (content.hasHeaders()) { + email.setHeaders(content.headers()); } - email.setEmailTags(emailTags); + email.setEmailTags(request.emailTags()); email.setInsights(SesMessageInsights.build(envelope, SesRecipientEvents.classify(envelope, suppressedReasons, rejected), email.getSentAt())); if (rejected) { @@ -280,20 +297,20 @@ public class SesService { } sentEmailService.record(region, messageId, email); - List relayedTo = filterUnsuppressed(toAddresses, suppressedReasons); - List relayedCc = filterUnsuppressed(ccAddresses, suppressedReasons); - List relayedBcc = filterUnsuppressed(bccAddresses, suppressedReasons); + List relayedTo = filterUnsuppressed(request.toAddresses(), suppressedReasons); + List relayedCc = filterUnsuppressed(request.ccAddresses(), suppressedReasons); + List relayedBcc = filterUnsuppressed(request.bccAddresses(), suppressedReasons); if (!rejected && sizeOf(relayedTo) + sizeOf(relayedCc) + sizeOf(relayedBcc) > 0) { smtpRelay.relay(SmtpRelay.RelayMessage.builder(source) .returnPath(effectiveReturnPath) .to(relayedTo) .cc(relayedCc) .bcc(relayedBcc) - .replyTo(replyToAddresses) - .subject(subject) - .bodyText(bodyText) - .bodyHtml(bodyHtml) - .headers(additionalHeaders) + .replyTo(request.replyToAddresses()) + .subject(content.subject()) + .bodyText(content.bodyText()) + .bodyHtml(content.bodyHtml()) + .headers(content.headers()) .messageId(messageId) .build()); } else { @@ -303,18 +320,19 @@ public class SesService { if (!rejected) { LOG.infov("SES email sent: from={0}, to={1}, subject={2}, messageId={3}", - source, toAddresses, subject, messageId); + source, request.toAddresses(), content.subject(), messageId); } - publishSendEvents(effectiveConfigSet, messageId, source, subject, - toAddresses, ccAddresses, bccAddresses, envelope, - suppressedReasons, rejected, emailTags, additionalHeaders, region); + publishSendEvents(effectiveConfigSet, messageId, source, content.subject(), + request.toAddresses(), request.ccAddresses(), request.bccAddresses(), envelope, + suppressedReasons, rejected, request.emailTags(), content.headers(), region); return messageId; } - public String sendRawEmail(String source, List destinations, String rawMessage, - String returnPath, String configurationSetName, List emailTags, - ListManagementOptions listManagement, String tenantName, String region) { - if (rawMessage == null || rawMessage.isBlank()) { + private String sendRawEmail(SendEmailRequest request, EmailContent.Raw raw) { + String source = request.source(); + String region = request.region(); + List destinations = request.recipients(); + if (raw.data() == null || raw.data().isBlank()) { throw new AwsException("InvalidParameterValue", "RawMessage.Data is required.", 400); } boolean hasExplicitDestinations = destinations != null && !destinations.isEmpty(); @@ -322,19 +340,19 @@ public class SesService { // The MIME headers are always parsed: X-SES-CONFIGURATION-SET can name the configuration // set that decides whether events are published at all, so the configuration set cannot be // resolved before the message has been read. - SmtpRelay.ParsedRawMessage parsed = SmtpRelay.parseRawMessage(rawMessage); + SmtpRelay.ParsedRawMessage parsed = SmtpRelay.parseRawMessage(raw.data()); SmtpRelay.RawMessageHeaders headers = parsed.headers(); // AWS accepts the configuration set either as a request field or as the // X-SES-CONFIGURATION-SET header on the message itself; the request field wins. - String requestedConfigSet = firstNonBlank(configurationSetName, headers.configurationSet()); + String requestedConfigSet = firstNonBlank(request.configurationSetName(), headers.configurationSet()); String effectiveConfigSet = resolveDefaultConfigurationSet(requestedConfigSet, source, region); configSetService.validateForSending(effectiveConfigSet, region); // Message tags work differently: AWS uses only the request field's tags when both are // present and does not join the two sets, so the header tags apply only when no tag was // passed as a parameter. - List effectiveTags = (emailTags == null || emailTags.isEmpty()) + List effectiveTags = (request.emailTags() == null || request.emailTags().isEmpty()) ? headers.messageTags() - : emailTags; + : request.emailTags(); String effectiveSource = sourceOmitted && !headers.from().isBlank() ? headers.from() : source; @@ -355,7 +373,7 @@ public class SesService { } List effectiveDestinations = hasExplicitDestinations ? destinations - : allRecipients(headers.to(), headers.cc(), headers.bcc()); + : SendEmailRequest.recipients(headers.to(), headers.cc(), headers.bcc()); if (effectiveDestinations.isEmpty()) { throw new AwsException("InvalidParameterValue", "At least one destination address is required.", 400); @@ -366,7 +384,7 @@ public class SesService { collectSuppressedReasons(effectiveDestinations, effectiveConfigSet, region)); // putIfAbsent so a suppression-list reason already set for an address (e.g. COMPLAINT) wins // over the list-management opt-out and keeps its synthetic event type. - contactService.collectListManagementOptOuts(effectiveDestinations, listManagement, region, + contactService.collectListManagementOptOuts(effectiveDestinations, request.listManagement(), region, SesService::extractEmailAddress) .forEach(suppressedReasons::putIfAbsent); @@ -383,19 +401,19 @@ public class SesService { // own headers, and that header's value reaches here unparsed, so it is dropped; an envelope // read off the headers is a list of parsed addresses and carries no message text. String effectiveReturnPath = rejected - ? firstNonBlank(returnPath, effectiveSource) - : firstNonBlank(headers.returnPath(), returnPath, effectiveSource); - SentEmail email = new SentEmail(messageId, region, effectiveSource, effectiveDestinations, rawMessage); + ? firstNonBlank(request.returnPath(), effectiveSource) + : firstNonBlank(headers.returnPath(), request.returnPath(), effectiveSource); + SentEmail email = new SentEmail(messageId, region, effectiveSource, effectiveDestinations, raw.data()); email.setReturnPath(effectiveReturnPath); email.setConfigurationSetName(firstNonBlank(effectiveConfigSet)); - email.setTenantName(firstNonBlank(tenantName)); + email.setTenantName(firstNonBlank(request.tenantName())); // The MIME subject is already parsed for the published events; store it too so // GetMessageInsights reports it for a raw send as it does for a simple one. The parser // yields "" for a missing header, and an absent subject must stay absent. email.setSubject(firstNonBlank(headers.subject())); // A rejected message publishes only the tags that came with the request, so the stored // record keeps the same set: tags read off its headers must not resurface through insights. - email.setEmailTags(rejected ? requestTags(emailTags) : effectiveTags); + email.setEmailTags(rejected ? requestTags(request.emailTags()) : effectiveTags); email.setInsights(SesMessageInsights.build(effectiveDestinations, SesRecipientEvents.classify(effectiveDestinations, suppressedReasons, rejected), email.getSentAt())); @@ -407,7 +425,7 @@ public class SesService { List relayedDestinations = filterUnsuppressed(effectiveDestinations, suppressedReasons); if (!rejected && !relayedDestinations.isEmpty()) { smtpRelay.relayRaw(new SmtpRelay.RawRelayMessage(effectiveSource, effectiveReturnPath, - relayedDestinations, rawMessage, messageId)); + relayedDestinations, raw.data(), messageId)); } else { LOG.infov("SES raw email accepted but not relayed ({0}): messageId={1}", rejected ? "content rejected" : "all recipients suppressed", messageId); @@ -424,24 +442,11 @@ public class SesService { publishSendEvents(effectiveConfigSet, messageId, effectiveSource, headers.subject(), publishedTo, publishedCc, publishedBcc, effectiveDestinations, - suppressedReasons, rejected, rejected ? requestTags(emailTags) : effectiveTags, List.of(), region); + suppressedReasons, rejected, rejected ? requestTags(request.emailTags()) : effectiveTags, + List.of(), region); return messageId; } - private static List allRecipients(List to, List cc, List bcc) { - List all = new ArrayList<>(); - if (to != null) { - all.addAll(to); - } - if (cc != null) { - all.addAll(cc); - } - if (bcc != null) { - all.addAll(bcc); - } - return all; - } - private void publishSendEvents(String configurationSetName, String messageId, String source, String subject, List toAddresses, List ccAddresses, List bccAddresses, @@ -1429,20 +1434,6 @@ public class SesService { return effective.contains(entry.getReason()) ? entry.getReason() : null; } - public String sendTemplatedEmail(String source, List toAddresses, List ccAddresses, - List bccAddresses, List replyToAddresses, - String returnPath, String templateName, JsonNode templateData, - String configurationSetName, List emailTags, - List additionalHeaders, - ListManagementOptions listManagement, String tenantName, String region) { - EmailTemplate template = templateService.getTemplate(templateName, region); - return sendInlineTemplatedEmail(source, toAddresses, ccAddresses, bccAddresses, - replyToAddresses, returnPath, template.getSubject(), template.getTextPart(), - template.getHtmlPart(), templateData, - configurationSetName, emailTags, additionalHeaders, listManagement, - tenantName, region); - } - /** * Also called by the controller ahead of the tenant send gate: AWS reports an empty inline * template before it looks the tenant up (probe-confirmed), so the check must not stay behind @@ -1458,48 +1449,23 @@ public class SesService { } } - public String sendInlineTemplatedEmail(String source, List toAddresses, List ccAddresses, - List bccAddresses, List replyToAddresses, - String returnPath, - String subject, String textPart, String htmlPart, - JsonNode templateData, - String configurationSetName, List emailTags, - List additionalHeaders, - ListManagementOptions listManagement, String tenantName, String region) { - requireInlineTemplateContent(subject, textPart, htmlPart); - return sendEmail(source, toAddresses, ccAddresses, bccAddresses, replyToAddresses, returnPath, - SesTemplateService.applyTemplateData(subject, templateData), - SesTemplateService.applyTemplateData(textPart, templateData), - SesTemplateService.applyTemplateData(htmlPart, templateData), - configurationSetName, emailTags, additionalHeaders, listManagement, - tenantName, region); - } - - public List sendBulkTemplatedEmail(String source, - List replyToAddresses, - String returnPath, - String subject, String textPart, String htmlPart, - JsonNode defaultTemplateData, - List entries, - String configurationSetName, - List defaultEmailTags, - List defaultHeaders, - String tenantName, String region) { - if (source == null || source.isBlank()) { + public List 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(subject, textPart, htmlPart); - if (entries == null || entries.isEmpty()) { + requireInlineTemplateContent(template.subject(), template.textPart(), template.htmlPart()); + if (request.entries() == null || request.entries().isEmpty()) { throw new AwsException("InvalidParameterValue", "At least one destination entry is required.", 400); } - configSetService.validateForSending(configurationSetName, region); - if (entries.size() > MAX_BULK_DESTINATIONS) { + configSetService.validateForSending(request.configurationSetName(), request.region()); + if (request.entries().size() > MAX_BULK_DESTINATIONS) { throw new AwsException("MessageRejected", - "Number of destinations (" + entries.size() + ") exceeds the maximum of " + "Number of destinations (" + request.entries().size() + ") exceeds the maximum of " + MAX_BULK_DESTINATIONS + ".", 400); } - for (BulkEmailEntry entry : entries) { + for (BulkEmailEntry entry : request.entries()) { int recipientCount = sizeOf(entry.toAddresses()) + sizeOf(entry.ccAddresses()) + sizeOf(entry.bccAddresses()); @@ -1510,21 +1476,30 @@ public class SesService { } } - List results = new ArrayList<>(entries.size()); - for (BulkEmailEntry entry : entries) { + List results = new ArrayList<>(request.entries().size()); + for (BulkEmailEntry entry : request.entries()) { try { - JsonNode merged = mergeTemplateData(defaultTemplateData, entry.replacementTemplateData()); - List mergedTags = mergeEmailTags(defaultEmailTags, entry.replacementEmailTags()); - List mergedHeaders = mergeHeaders(defaultHeaders, entry.replacementHeaders()); + JsonNode merged = mergeTemplateData(template.templateData(), entry.replacementTemplateData()); + List mergedTags = mergeEmailTags(request.defaultEmailTags(), entry.replacementEmailTags()); + List mergedHeaders = mergeHeaders(template.headers(), entry.replacementHeaders()); + EmailContent.Simple rendered = SesTemplateService.render(new EmailContent.InlineTemplate( + template.subject(), template.textPart(), template.htmlPart(), merged, mergedHeaders)); // SendBulkEmail has no ListManagementOptions field, so list-managed suppression - // does not apply to bulk sends. - String messageId = sendEmail(source, - entry.toAddresses(), entry.ccAddresses(), entry.bccAddresses(), - replyToAddresses, returnPath, - SesTemplateService.applyTemplateData(subject, merged), - SesTemplateService.applyTemplateData(textPart, merged), - SesTemplateService.applyTemplateData(htmlPart, merged), - configurationSetName, mergedTags, mergedHeaders, null, tenantName, region); + // does not apply to bulk sends and the entry request leaves it unset. + SendEmailRequest entryRequest = SendEmailRequest.builder() + .source(request.source()) + .toAddresses(entry.toAddresses()) + .ccAddresses(entry.ccAddresses()) + .bccAddresses(entry.bccAddresses()) + .replyToAddresses(request.replyToAddresses()) + .returnPath(request.returnPath()) + .configurationSetName(request.configurationSetName()) + .emailTags(mergedTags) + .tenantName(request.tenantName()) + .region(request.region()) + .content(rendered) + .build(); + String messageId = sendSimpleEmail(entryRequest, rendered); results.add(BulkEmailEntryResult.success(messageId)); } catch (AwsException e) { results.add(BulkEmailEntryResult.failure( diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateService.java index 6471a08374..f53bc6249c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateService.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.ses.model.EmailContent; import io.github.hectorvent.floci.services.ses.model.EmailTemplate; import io.github.hectorvent.floci.services.ses.model.Tag; import jakarta.enterprise.context.ApplicationScoped; @@ -90,6 +91,12 @@ public class SesTemplateService { "Template " + templateName + " does not exist.", 400)); } + EmailContent.InlineTemplate inline(EmailContent.Template template, String region) { + EmailTemplate stored = getTemplate(template.templateName(), region); + return new EmailContent.InlineTemplate(stored.getSubject(), stored.getTextPart(), + stored.getHtmlPart(), template.templateData(), template.headers()); + } + public EmailTemplate updateTemplate(EmailTemplate template, String region) { validateTemplate(template); String key = templateKey(region, template.getTemplateName()); @@ -249,6 +256,14 @@ public class SesTemplateService { return node; } + static EmailContent.Simple render(EmailContent.InlineTemplate template) { + return new EmailContent.Simple( + applyTemplateData(template.subject(), template.templateData()), + applyTemplateData(template.textPart(), template.templateData()), + applyTemplateData(template.htmlPart(), template.templateData()), + template.headers()); + } + static String applyTemplateData(String text, JsonNode data) { if (text == null || text.isEmpty()) { return text; diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/EmailContent.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/EmailContent.java new file mode 100644 index 0000000000..f7ad3a7529 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/EmailContent.java @@ -0,0 +1,45 @@ +package io.github.hectorvent.floci.services.ses.model; + +import com.fasterxml.jackson.databind.JsonNode; + +import java.util.List; + +/** + * The body of a send, mirroring the v2 {@code EmailContent} union: exactly one of a simple + * message, a template, or a raw MIME message. A stored template and inline template content are + * separate variants here, since the controllers have already resolved the v2 selector + * (TemplateName, TemplateArn or TemplateContent) by the time a request is built. + */ +public sealed interface EmailContent { + + record Simple(String subject, String bodyText, String bodyHtml, List headers) + implements EmailContent { + + public boolean hasHeaders() { + return headers != null && !headers.isEmpty(); + } + + public Simple withSafeHeaders() { + if (!hasHeaders()) { + return this; + } + return new Simple(subject, bodyText, bodyHtml, headers.stream().filter(MessageHeader::isSafe).toList()); + } + } + + record Template(String templateName, JsonNode templateData, List headers) + implements EmailContent { + } + + record InlineTemplate(String subject, String textPart, String htmlPart, JsonNode templateData, + List headers) implements EmailContent { + } + + /** + * A raw send reads the envelope's to, cc and bcc as one flat destination list, and falls back + * to the MIME headers when that list is empty. It ignores {@code replyToAddresses}: the + * message carries its own Reply-To header. + */ + record Raw(String data) implements EmailContent { + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/SendBulkEmailRequest.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/SendBulkEmailRequest.java new file mode 100644 index 0000000000..9b1aa68146 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/SendBulkEmailRequest.java @@ -0,0 +1,61 @@ +package io.github.hectorvent.floci.services.ses.model; + +import java.util.List; +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. + */ +public record SendBulkEmailRequest( + String source, + List replyToAddresses, + String returnPath, + String configurationSetName, + List defaultEmailTags, + String tenantName, + String region, + EmailContent.InlineTemplate defaultContent, + List entries) { + + public SendBulkEmailRequest { + Objects.requireNonNull(defaultContent, "defaultContent"); + } + + public static Builder builder() { + return new Builder(); + } + + public static final class Builder { + private String source; + private List replyToAddresses = List.of(); + private String returnPath; + private String configurationSetName; + private List defaultEmailTags = List.of(); + private String tenantName; + private String region; + private EmailContent.InlineTemplate defaultContent; + private List entries = List.of(); + + private Builder() { + } + + public Builder source(String source) { this.source = source; return this; } + public Builder replyToAddresses(List replyToAddresses) { this.replyToAddresses = replyToAddresses; return this; } + public Builder returnPath(String returnPath) { this.returnPath = returnPath; return this; } + public Builder configurationSetName(String configurationSetName) { this.configurationSetName = configurationSetName; return this; } + public Builder defaultEmailTags(List 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 entries(List entries) { this.entries = entries; return this; } + + public SendBulkEmailRequest build() { + return new SendBulkEmailRequest(source, replyToAddresses, returnPath, configurationSetName, + defaultEmailTags, tenantName, region, defaultContent, entries); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/SendEmailRequest.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/SendEmailRequest.java new file mode 100644 index 0000000000..b5cda71405 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/SendEmailRequest.java @@ -0,0 +1,112 @@ +package io.github.hectorvent.floci.services.ses.model; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * The service-level input of a single send, shaped like the v2 {@code SendEmailRequest}: an + * envelope plus an {@link EmailContent}. It is built by the v1 Query handler, the v2 REST + * controller and Cognito, and rebuilt inside SesService whenever the content is rendered or + * sanitized, so the request always carries the content being sent. It is not a wire shape: each + * caller translates its own request into these fields (v2 {@code FromEmailAddress} into + * {@code source}, {@code FeedbackForwardingEmailAddress} into {@code returnPath}, v1 {@code Tags} + * into {@code emailTags}, v1 {@code SendRawEmail} {@code Destinations} into {@code toAddresses}), + * and a field a caller's API lacks keeps the builder default. + */ +public record SendEmailRequest( + String source, + List toAddresses, + List ccAddresses, + List bccAddresses, + List replyToAddresses, + String returnPath, + String configurationSetName, + List emailTags, + ListManagementOptions listManagement, + String tenantName, + String region, + EmailContent content) { + + public SendEmailRequest { + Objects.requireNonNull(content, "content"); + } + + public List recipients() { + return recipients(toAddresses, ccAddresses, bccAddresses); + } + + public static List recipients(List to, List cc, List bcc) { + List all = new ArrayList<>(); + if (to != null) { + all.addAll(to); + } + if (cc != null) { + all.addAll(cc); + } + if (bcc != null) { + all.addAll(bcc); + } + return all; + } + + public boolean hasRecipients() { + return !recipients().isEmpty(); + } + + public static Builder builder() { + return new Builder(); + } + + public Builder toBuilder() { + return new Builder() + .source(source) + .toAddresses(toAddresses) + .ccAddresses(ccAddresses) + .bccAddresses(bccAddresses) + .replyToAddresses(replyToAddresses) + .returnPath(returnPath) + .configurationSetName(configurationSetName) + .emailTags(emailTags) + .listManagement(listManagement) + .tenantName(tenantName) + .region(region) + .content(content); + } + + public static final class Builder { + private String source; + private List toAddresses = List.of(); + private List ccAddresses = List.of(); + private List bccAddresses = List.of(); + private List replyToAddresses = List.of(); + private String returnPath; + private String configurationSetName; + private List emailTags = List.of(); + private ListManagementOptions listManagement; + private String tenantName; + private String region; + private EmailContent content; + + private Builder() { + } + + public Builder source(String source) { this.source = source; return this; } + public Builder toAddresses(List toAddresses) { this.toAddresses = toAddresses; return this; } + public Builder ccAddresses(List ccAddresses) { this.ccAddresses = ccAddresses; return this; } + public Builder bccAddresses(List bccAddresses) { this.bccAddresses = bccAddresses; return this; } + public Builder replyToAddresses(List replyToAddresses) { this.replyToAddresses = replyToAddresses; return this; } + public Builder returnPath(String returnPath) { this.returnPath = returnPath; return this; } + public Builder configurationSetName(String configurationSetName) { this.configurationSetName = configurationSetName; return this; } + public Builder emailTags(List emailTags) { this.emailTags = emailTags; return this; } + public Builder listManagement(ListManagementOptions listManagement) { this.listManagement = listManagement; return this; } + public Builder tenantName(String tenantName) { this.tenantName = tenantName; return this; } + public Builder region(String region) { this.region = region; return this; } + public Builder content(EmailContent content) { this.content = content; return this; } + + public SendEmailRequest build() { + return new SendEmailRequest(source, toAddresses, ccAddresses, bccAddresses, replyToAddresses, + returnPath, configurationSetName, emailTags, listManagement, tenantName, region, content); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java index 7fb0cdecb8..8c040a90ac 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java @@ -17,6 +17,8 @@ import io.github.hectorvent.floci.services.lambda.LambdaService; import io.github.hectorvent.floci.services.lambda.model.InvocationType; import io.github.hectorvent.floci.services.lambda.model.InvokeResult; import io.github.hectorvent.floci.services.ses.SesService; +import io.github.hectorvent.floci.services.ses.model.EmailContent; +import io.github.hectorvent.floci.services.ses.model.SendEmailRequest; import io.github.hectorvent.floci.services.sns.SnsService; import io.github.hectorvent.floci.testing.MutableClock; import org.junit.jupiter.api.BeforeEach; @@ -45,7 +47,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -148,6 +149,18 @@ class CognitoLambdaTriggersTest { } } + private static void assertVerificationEmail(SesService ses, String to, String subject, String body) { + ArgumentCaptor captor = ArgumentCaptor.forClass(SendEmailRequest.class); + verify(ses).sendEmail(captor.capture()); + SendEmailRequest sent = captor.getValue(); + assertEquals(SendEmailRequest.builder() + .source(sent.source()) + .toAddresses(List.of(to)) + .region("us-east-1") + .content(new EmailContent.Simple(subject, body, null, List.of())) + .build(), sent); + } + private static InvokeResult rawPayload(String payload) { return new InvokeResult(200, null, payload.getBytes(StandardCharsets.UTF_8), null, "req-id"); } @@ -1396,12 +1409,7 @@ class CognitoLambdaTriggersTest { svc.signUp(client.getClientId(), "spike", "Spike@Test1", Map.of("email", "spike@example.com")); - verify(ses).sendEmail( - anyString(), eq(List.of("spike@example.com")), - eq(List.of()), eq(List.of()), eq(List.of()), isNull(), - eq("TRIGGER-FIRED"), - eq("TRIGGER-FIRED code=246962"), - any(), any(), eq(List.of()), eq(List.of()), any(), isNull(), anyString()); + assertVerificationEmail(ses, "spike@example.com", "TRIGGER-FIRED", "TRIGGER-FIRED code=246962"); } @Test @@ -1453,12 +1461,8 @@ class CognitoLambdaTriggersTest { // SignUp must still succeed and deliver the default message when CustomMessage errors. svc.signUp(client.getClientId(), "spike", "Spike@Test1", Map.of("email", "spike@example.com")); - verify(ses).sendEmail( - anyString(), eq(List.of("spike@example.com")), - any(), any(), any(), isNull(), - eq("Your verification code"), - eq("Your verification code is 246962."), - any(), any(), any(), any(), any(), isNull(), anyString()); + assertVerificationEmail(ses, "spike@example.com", "Your verification code", + "Your verification code is 246962."); } @Test @@ -1477,12 +1481,8 @@ class CognitoLambdaTriggersTest { svc.signUp(client.getClientId(), "spike", "Spike@Test1", Map.of("email", "spike@example.com")); verify(lambdaService, never()).invoke(anyString(), anyString(), any(byte[].class), any()); - verify(ses).sendEmail( - anyString(), eq(List.of("spike@example.com")), - any(), any(), any(), isNull(), - eq("Your verification code"), - eq("Your verification code is 246962."), - any(), any(), any(), any(), any(), isNull(), anyString()); + assertVerificationEmail(ses, "spike@example.com", "Your verification code", + "Your verification code is 246962."); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcherTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcherTest.java index 13e68bf03d..1c5056c87c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcherTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcherTest.java @@ -3,15 +3,20 @@ package io.github.hectorvent.floci.services.cognito.verification; import io.github.hectorvent.floci.services.cognito.model.CognitoUser; import io.github.hectorvent.floci.services.cognito.model.UserPool; import io.github.hectorvent.floci.services.ses.SesService; +import io.github.hectorvent.floci.services.ses.model.EmailContent; +import io.github.hectorvent.floci.services.ses.model.SendEmailRequest; import io.github.hectorvent.floci.services.sns.SnsService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.mockito.ArgumentMatchers.any; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; @@ -43,14 +48,13 @@ class CognitoMessageDispatcherTest { dispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); - verify(ses).sendEmail( - anyString(), - eq(List.of("alice@example.com")), - eq(List.of()), eq(List.of()), eq(List.of()), isNull(), - eq("Verify your account"), - eq("Hi! Your code is 123456."), - isNull(), isNull(), eq(List.of()), eq(List.of()), - isNull(), isNull(), eq("us-east-1")); + SendEmailRequest sent = sentEmail(); + assertEquals(SendEmailRequest.builder() + .source(sent.source()) + .toAddresses(List.of("alice@example.com")) + .region("us-east-1") + .content(new EmailContent.Simple("Verify your account", "Hi! Your code is 123456.", null, List.of())) + .build(), sent); verifyNoInteractions(sns); } @@ -118,12 +122,14 @@ class CognitoMessageDispatcherTest { dispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION, "111222", List.of("EMAIL")); - verify(ses).sendEmail( - anyString(), eq(List.of("alice@example.com")), - eq(List.of()), eq(List.of()), eq(List.of()), isNull(), - eq("Your verification code"), - eq("Your verification code is 111222."), - isNull(), isNull(), eq(List.of()), eq(List.of()), isNull(), isNull(), eq("us-east-1")); + SendEmailRequest sent = sentEmail(); + assertEquals(SendEmailRequest.builder() + .source(sent.source()) + .toAddresses(List.of("alice@example.com")) + .region("us-east-1") + .content(new EmailContent.Simple("Your verification code", "Your verification code is 111222.", + null, List.of())) + .build(), sent); } @Test @@ -134,12 +140,14 @@ class CognitoMessageDispatcherTest { dispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION, "999000", List.of("EMAIL")); - verify(ses).sendEmail( - anyString(), eq(List.of("alice@example.com")), - eq(List.of()), eq(List.of()), eq(List.of()), isNull(), - anyString(), - eq("Welcome, please verify.\nCode: 999000"), - isNull(), isNull(), eq(List.of()), eq(List.of()), isNull(), isNull(), eq("us-east-1")); + SendEmailRequest sent = sentEmail(); + assertNotNull(subject(sent)); + assertEquals(SendEmailRequest.builder() + .source(sent.source()) + .toAddresses(List.of("alice@example.com")) + .region("us-east-1") + .content(new EmailContent.Simple(subject(sent), "Welcome, please verify.\nCode: 999000", null, List.of())) + .build(), sent); } @Test @@ -150,9 +158,15 @@ class CognitoMessageDispatcherTest { dispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION, "444555", List.of()); - verify(ses).sendEmail(anyString(), eq(List.of("alice@example.com")), - any(), any(), any(), isNull(), anyString(), anyString(), isNull(), isNull(), any(), any(), - isNull(), isNull(), anyString()); + SendEmailRequest sent = sentEmail(); + assertNotNull(subject(sent)); + assertNotNull(bodyText(sent)); + assertEquals(SendEmailRequest.builder() + .source(sent.source()) + .toAddresses(List.of("alice@example.com")) + .region("us-east-1") + .content(new EmailContent.Simple(subject(sent), bodyText(sent), null, List.of())) + .build(), sent); verifyNoInteractions(sns); } @@ -169,6 +183,20 @@ class CognitoMessageDispatcherTest { verifyNoInteractions(ses); } + private SendEmailRequest sentEmail() { + ArgumentCaptor captor = ArgumentCaptor.forClass(SendEmailRequest.class); + verify(ses).sendEmail(captor.capture()); + return captor.getValue(); + } + + private static String subject(SendEmailRequest sent) { + return assertInstanceOf(EmailContent.Simple.class, sent.content()).subject(); + } + + private static String bodyText(SendEmailRequest sent) { + return assertInstanceOf(EmailContent.Simple.class, sent.content()).bodyText(); + } + private UserPool pool(Map template) { UserPool p = new UserPool(); p.setVerificationMessageTemplate(new HashMap<>(template)); diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesBulkV1IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesBulkV1IntegrationTest.java index 01cca6e66c..0809ae01b8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesBulkV1IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesBulkV1IntegrationTest.java @@ -155,7 +155,7 @@ class SesBulkV1IntegrationTest { @Test @Order(6) void sendBulkTemplatedEmail_perEntryMissingDestination_mapsToInvalidParameterValue() { - // An entry with only ReplacementTemplateData (no recipient) reaches sendEmail, + // An entry with only ReplacementTemplateData (no recipient) reaches the per-entry send, // which throws AwsException("InvalidParameterValue", ...). Expected per-entry // Status string in v1 is "InvalidParameterValue", not "Failed" or "InvalidParameter". // DefaultTemplateData supplies team so rendering succeeds before the recipient check. diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceListManagementTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceListManagementTest.java index 2070f34b0c..080d22da9d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceListManagementTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceListManagementTest.java @@ -4,8 +4,10 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.ses.model.Contact; +import io.github.hectorvent.floci.services.ses.model.EmailContent; import io.github.hectorvent.floci.services.ses.model.ListManagementOptions; import io.github.hectorvent.floci.services.ses.model.MessageHeader; +import io.github.hectorvent.floci.services.ses.model.SendEmailRequest; import io.github.hectorvent.floci.services.ses.model.Topic; import io.github.hectorvent.floci.services.ses.model.TopicPreference; import org.junit.jupiter.api.BeforeEach; @@ -64,8 +66,13 @@ class SesServiceListManagementTest { } private void send(List to, String topicName) { - service.sendEmail(FROM, to, null, null, null, null, "Subject", "body", null, - null, List.of(), List.of(), new ListManagementOptions(LIST, topicName), null, REGION); + service.sendEmail(SendEmailRequest.builder() + .source(FROM) + .toAddresses(to) + .listManagement(new ListManagementOptions(LIST, topicName)) + .region(REGION) + .content(new EmailContent.Simple("Subject", "body", null, List.of())) + .build()); } private SmtpRelay.RelayMessage capturedRelay() { @@ -122,9 +129,13 @@ class SesServiceListManagementTest { @Test void nonExistentContactList_failsTheSend() { AwsException ex = assertThrows(AwsException.class, () -> - service.sendEmail(FROM, List.of("sportsin@example.com"), null, null, null, null, - "Subject", "body", null, null, List.of(), List.of(), - new ListManagementOptions("ghost-list", null), null, REGION)); + service.sendEmail(SendEmailRequest.builder() + .source(FROM) + .toAddresses(List.of("sportsin@example.com")) + .listManagement(new ListManagementOptions("ghost-list", null)) + .region(REGION) + .content(new EmailContent.Simple("Subject", "body", null, List.of())) + .build())); assertEquals(404, ex.getHttpStatus()); } @@ -132,9 +143,13 @@ class SesServiceListManagementTest { void unknownTopic_failsTheSend() { // A TopicName not defined on the list is rejected rather than silently skipping suppression. AwsException ex = assertThrows(AwsException.class, () -> - service.sendEmail(FROM, List.of("sportsin@example.com"), null, null, null, null, - "Subject", "body", null, null, List.of(), List.of(), - new ListManagementOptions(LIST, "GhostTopic"), null, REGION)); + service.sendEmail(SendEmailRequest.builder() + .source(FROM) + .toAddresses(List.of("sportsin@example.com")) + .listManagement(new ListManagementOptions(LIST, "GhostTopic")) + .region(REGION) + .content(new EmailContent.Simple("Subject", "body", null, List.of())) + .build())); assertEquals(400, ex.getHttpStatus()); } @@ -142,17 +157,26 @@ class SesServiceListManagementTest { void noListManagementOptions_leavesRecipientsUntouched() { // Without ListManagementOptions the contact list is never consulted: an unsubscribed contact // is not suppressed and no contact is auto-created. - service.sendEmail(FROM, List.of("unsub@example.com"), null, null, null, null, - "Subject", "body", null, null, List.of(), List.of(), null, null, REGION); + service.sendEmail(SendEmailRequest.builder() + .source(FROM) + .toAddresses(List.of("unsub@example.com")) + .region(REGION) + .content(new EmailContent.Simple("Subject", "body", null, List.of())) + .build()); assertEquals(List.of("unsub@example.com"), capturedRelayTo()); } @Test void singleRecipient_replacesUnsubscribePlaceholder() { // newbie is not a contact (auto-created, Sports defaults OPT_IN) so the send reaches the relay. - service.sendEmail(FROM, List.of("newbie@example.com"), null, null, null, null, - "Subject", "text", "

Unsub: {{amazonSESUnsubscribeUrl}}

", - null, List.of(), List.of(), new ListManagementOptions(LIST, "Sports"), null, REGION); + service.sendEmail(SendEmailRequest.builder() + .source(FROM) + .toAddresses(List.of("newbie@example.com")) + .listManagement(new ListManagementOptions(LIST, "Sports")) + .region(REGION) + .content(new EmailContent.Simple("Subject", "text", "

Unsub: {{amazonSESUnsubscribeUrl}}

", + List.of())) + .build()); String html = capturedRelayBodyHtml(); assertTrue(html.contains("http://localhost:4566/_aws/ses/unsubscribe?"), html); assertTrue(html.contains("contactList=" + LIST), html); @@ -162,9 +186,14 @@ class SesServiceListManagementTest { @Test void multiRecipient_doesNotReplacePlaceholder() { - service.sendEmail(FROM, List.of("newbie@example.com", "sportsin@example.com"), null, null, null, - null, "Subject", "text", "

Unsub: {{amazonSESUnsubscribeUrl}}

", - null, List.of(), List.of(), new ListManagementOptions(LIST, "Sports"), null, REGION); + service.sendEmail(SendEmailRequest.builder() + .source(FROM) + .toAddresses(List.of("newbie@example.com", "sportsin@example.com")) + .listManagement(new ListManagementOptions(LIST, "Sports")) + .region(REGION) + .content(new EmailContent.Simple("Subject", "text", "

Unsub: {{amazonSESUnsubscribeUrl}}

", + List.of())) + .build()); assertTrue(capturedRelayBodyHtml().contains("{{amazonSESUnsubscribeUrl}}"), "multi-recipient send must not inject the unsubscribe link"); } @@ -215,9 +244,13 @@ class SesServiceListManagementTest { @Test void singleRecipient_addsListUnsubscribeHeadersToRelay() { - service.sendEmail(FROM, List.of("newbie@example.com"), null, null, null, null, - "Subject", "text", "

x

", null, List.of(), List.of(), - new ListManagementOptions(LIST, "Sports"), null, REGION); + service.sendEmail(SendEmailRequest.builder() + .source(FROM) + .toAddresses(List.of("newbie@example.com")) + .listManagement(new ListManagementOptions(LIST, "Sports")) + .region(REGION) + .content(new EmailContent.Simple("Subject", "text", "

x

", List.of())) + .build()); List headers = capturedRelayHeaders(); assertTrue(headers.stream().anyMatch(h -> "List-Unsubscribe".equals(h.name()) && h.value().contains("/_aws/ses/unsubscribe")), "List-Unsubscribe header must reach the relay"); @@ -227,10 +260,14 @@ class SesServiceListManagementTest { @Test void callerSuppliedUnsubscribeHeader_isOverriddenNotDuplicated() { - service.sendEmail(FROM, List.of("newbie@example.com"), null, null, null, null, - "Subject", "text", "

x

", null, List.of(), - List.of(new MessageHeader("List-Unsubscribe", "")), - new ListManagementOptions(LIST, "Sports"), null, REGION); + service.sendEmail(SendEmailRequest.builder() + .source(FROM) + .toAddresses(List.of("newbie@example.com")) + .listManagement(new ListManagementOptions(LIST, "Sports")) + .region(REGION) + .content(new EmailContent.Simple("Subject", "text", "

x

", + List.of(new MessageHeader("List-Unsubscribe", "")))) + .build()); long count = capturedRelayHeaders().stream() .filter(h -> "List-Unsubscribe".equalsIgnoreCase(h.name())).count(); assertEquals(1L, count); diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java index db730da624..8dbfb9ab99 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java @@ -4,7 +4,9 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; import io.github.hectorvent.floci.services.ses.model.CustomVerificationEmailTemplate; +import io.github.hectorvent.floci.services.ses.model.EmailContent; import io.github.hectorvent.floci.services.ses.model.InsightsEvent; +import io.github.hectorvent.floci.services.ses.model.SendEmailRequest; import io.github.hectorvent.floci.services.ses.model.SentEmail; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -123,13 +125,15 @@ class SesServiceSmtpTest { @Test void sendEmail_callsRelayWithAllFields() { - String messageId = service.sendEmail("from@example.com", - List.of("to@example.com"), - List.of("cc@example.com"), - List.of("bcc@example.com"), - List.of("reply@example.com"), - null, - "Subject", "text body", "

html

", null, List.of(), List.of(), null, null, "us-east-1"); + String messageId = service.sendEmail(SendEmailRequest.builder() + .source("from@example.com") + .toAddresses(List.of("to@example.com")) + .ccAddresses(List.of("cc@example.com")) + .bccAddresses(List.of("bcc@example.com")) + .replyToAddresses(List.of("reply@example.com")) + .region("us-east-1") + .content(new EmailContent.Simple("Subject", "text body", "

html

", List.of())) + .build()); SmtpRelay.RelayMessage relayed = capturedRelay(); assertEquals("from@example.com", relayed.from()); @@ -146,9 +150,12 @@ class SesServiceSmtpTest { @Test void sendEmail_storesAndRelays() { - String messageId = service.sendEmail("from@example.com", - List.of("to@example.com"), null, null, null, null, - "Subject", "text", null, null, List.of(), List.of(), null, null, "us-east-1"); + String messageId = service.sendEmail(SendEmailRequest.builder() + .source("from@example.com") + .toAddresses(List.of("to@example.com")) + .region("us-east-1") + .content(new EmailContent.Simple("Subject", "text", null, List.of())) + .build()); assertNotNull(messageId); assertFalse(emailStore.scan(k -> true).isEmpty()); @@ -157,18 +164,25 @@ class SesServiceSmtpTest { @Test void sendEmail_noReturnPath_fallsBackToSource() { - service.sendEmail("from@example.com", - List.of("to@example.com"), null, null, null, null, - "Subject", "text", null, null, List.of(), List.of(), null, null, "us-east-1"); + service.sendEmail(SendEmailRequest.builder() + .source("from@example.com") + .toAddresses(List.of("to@example.com")) + .region("us-east-1") + .content(new EmailContent.Simple("Subject", "text", null, List.of())) + .build()); assertEquals("from@example.com", capturedRelay().returnPath()); } @Test void sendEmail_explicitReturnPath_isRelayedAndStored() { - String messageId = service.sendEmail("from@example.com", - List.of("to@example.com"), null, null, null, "bounces@example.com", - "Subject", "text", null, null, List.of(), List.of(), null, null, "us-east-1"); + String messageId = service.sendEmail(SendEmailRequest.builder() + .source("from@example.com") + .toAddresses(List.of("to@example.com")) + .returnPath("bounces@example.com") + .region("us-east-1") + .content(new EmailContent.Simple("Subject", "text", null, List.of())) + .build()); assertEquals("bounces@example.com", capturedRelay().returnPath()); assertEquals("bounces@example.com", storedEmail(messageId).getReturnPath()); @@ -181,8 +195,13 @@ class SesServiceSmtpTest { String raw = "From: from@example.com\r\nTo: to@example.com\r\nReturn-Path: \r\n" + "Subject: " + SesContentScan.signature() + "\r\n\r\nbody\r\n"; - String messageId = service.sendRawEmail("from@example.com", List.of("to@example.com"), raw, - "bounces@example.com", null, List.of(), null, null, "us-east-1"); + String messageId = service.sendEmail(SendEmailRequest.builder() + .source("from@example.com") + .toAddresses(List.of("to@example.com")) + .returnPath("bounces@example.com") + .region("us-east-1") + .content(new EmailContent.Raw(raw)) + .build()); assertEquals("bounces@example.com", storedEmail(messageId).getReturnPath()); assertEquals("Bad content", storedEmail(messageId).getRejectReason()); @@ -195,8 +214,12 @@ class SesServiceSmtpTest { // rather than recorded and relayed unseen. String raw = "Content-Type: message/rfc822\r\n\r\n".repeat(100_000) + "Subject: deep\r\n\r\nx\r\n"; - AwsException e = assertThrows(AwsException.class, () -> service.sendRawEmail("from@example.com", - List.of("to@example.com"), raw, null, null, List.of(), null, null, "us-east-1")); + AwsException e = assertThrows(AwsException.class, () -> service.sendEmail(SendEmailRequest.builder() + .source("from@example.com") + .toAddresses(List.of("to@example.com")) + .region("us-east-1") + .content(new EmailContent.Raw(raw)) + .build())); assertEquals(400, e.getHttpStatus()); assertTrue(sentEmails.listAll().isEmpty()); @@ -205,8 +228,12 @@ class SesServiceSmtpTest { @Test void sendRawEmail_callsRelayRaw() { - String messageId = service.sendRawEmail("from@example.com", - List.of("to@example.com"), "raw MIME", null, null, List.of(), null, null, "us-east-1"); + String messageId = service.sendEmail(SendEmailRequest.builder() + .source("from@example.com") + .toAddresses(List.of("to@example.com")) + .region("us-east-1") + .content(new EmailContent.Raw("raw MIME")) + .build()); SmtpRelay.RawRelayMessage relayed = capturedRawRelay(); assertEquals("from@example.com", relayed.from()); @@ -222,8 +249,13 @@ class SesServiceSmtpTest { + "Return-Path: \r\n" + "Subject: x\r\n\r\nbody"; - String messageId = service.sendRawEmail("from@example.com", List.of("to@example.com"), raw, - "request-bounces@example.com", null, List.of(), null, null, "us-east-1"); + String messageId = service.sendEmail(SendEmailRequest.builder() + .source("from@example.com") + .toAddresses(List.of("to@example.com")) + .returnPath("request-bounces@example.com") + .region("us-east-1") + .content(new EmailContent.Raw(raw)) + .build()); assertEquals("mime-bounces@example.com", capturedRawRelay().returnPath()); assertEquals("mime-bounces@example.com", storedEmail(messageId).getReturnPath()); @@ -233,28 +265,64 @@ class SesServiceSmtpTest { void sendRawEmail_noReturnPathHeader_usesRequestField() { String raw = "From: from@example.com\r\nTo: to@example.com\r\nSubject: x\r\n\r\nbody"; - service.sendRawEmail("from@example.com", List.of("to@example.com"), raw, - "request-bounces@example.com", null, List.of(), null, null, "us-east-1"); + service.sendEmail(SendEmailRequest.builder() + .source("from@example.com") + .toAddresses(List.of("to@example.com")) + .returnPath("request-bounces@example.com") + .region("us-east-1") + .content(new EmailContent.Raw(raw)) + .build()); assertEquals("request-bounces@example.com", capturedRawRelay().returnPath()); } @Test void sendRawEmail_storesAndRelays() { - String messageId = service.sendRawEmail("from@example.com", - List.of("to@example.com"), "raw", null, null, List.of(), null, null, "us-east-1"); + String messageId = service.sendEmail(SendEmailRequest.builder() + .source("from@example.com") + .toAddresses(List.of("to@example.com")) + .region("us-east-1") + .content(new EmailContent.Raw("raw")) + .build()); assertNotNull(messageId); assertFalse(emailStore.scan(k -> true).isEmpty()); verify(smtpRelay).relayRaw(any(SmtpRelay.RawRelayMessage.class)); } + // Template errors (a missing stored template, empty inline content) are reported before the + // envelope checks, so envelope validation must not move ahead of the content switch. + @Test + void sendEmail_unknownTemplate_reportedBeforeMissingSource() { + AwsException e = assertThrows(AwsException.class, () -> service.sendEmail(SendEmailRequest.builder() + .region("us-east-1") + .content(new EmailContent.Template("ghost", null, List.of())) + .build())); + + assertEquals("TemplateDoesNotExist", e.getErrorCode()); + } + + @Test + void sendEmail_emptyInlineTemplate_reportedBeforeMissingSource() { + AwsException e = assertThrows(AwsException.class, () -> service.sendEmail(SendEmailRequest.builder() + .region("us-east-1") + .content(new EmailContent.InlineTemplate(null, null, null, null, List.of())) + .build())); + + assertEquals("InvalidTemplate", e.getErrorCode()); + } + @Test void sendEmail_relayReceivesCorrectFieldsWithNulls() { - service.sendEmail("from@example.com", - List.of("to@example.com"), - null, null, null, null, - "Subject", null, "

html only

", null, List.of(), List.of(), null, null, "us-east-1"); + service.sendEmail(SendEmailRequest.builder() + .source("from@example.com") + .toAddresses(List.of("to@example.com")) + .ccAddresses(null) + .bccAddresses(null) + .replyToAddresses(null) + .region("us-east-1") + .content(new EmailContent.Simple("Subject", null, "

html only

", List.of())) + .build()); SmtpRelay.RelayMessage relayed = capturedRelay(); assertEquals(List.of("to@example.com"), relayed.to()); @@ -270,11 +338,13 @@ class SesServiceSmtpTest { suppression.putSuppressedDestination("us-east-1", "to@example.com", "BOUNCE"); suppression.putSuppressedDestination("us-east-1", "cc@example.com", "COMPLAINT"); - String messageId = service.sendEmail("from@example.com", - List.of("to@example.com"), - List.of("cc@example.com"), - null, null, null, - "Subject", "text body", null, null, List.of(), List.of(), null, null, "us-east-1"); + String messageId = service.sendEmail(SendEmailRequest.builder() + .source("from@example.com") + .toAddresses(List.of("to@example.com")) + .ccAddresses(List.of("cc@example.com")) + .region("us-east-1") + .content(new EmailContent.Simple("Subject", "text body", null, List.of())) + .build()); assertNotNull(messageId); assertFalse(emailStore.scan(k -> true).isEmpty(), @@ -287,11 +357,13 @@ class SesServiceSmtpTest { // Only suppress one of the To recipients; the other should still reach the relay. suppression.putSuppressedDestination("us-east-1", "suppressed@example.com", "BOUNCE"); - service.sendEmail("from@example.com", - List.of("to@example.com", "suppressed@example.com"), - List.of("cc-keep@example.com"), - null, null, null, - "Subject", "text body", null, null, List.of(), List.of(), null, null, "us-east-1"); + service.sendEmail(SendEmailRequest.builder() + .source("from@example.com") + .toAddresses(List.of("to@example.com", "suppressed@example.com")) + .ccAddresses(List.of("cc-keep@example.com")) + .region("us-east-1") + .content(new EmailContent.Simple("Subject", "text body", null, List.of())) + .build()); SmtpRelay.RelayMessage relayed = capturedRelay(); assertEquals(List.of("to@example.com"), relayed.to()); @@ -302,8 +374,12 @@ class SesServiceSmtpTest { void sendRawEmail_allRecipientsSuppressed_skipsRelayRawButStillStores() { suppression.putSuppressedDestination("us-east-1", "to@example.com", "BOUNCE"); - String messageId = service.sendRawEmail("from@example.com", - List.of("to@example.com"), "raw MIME", null, null, List.of(), null, null, "us-east-1"); + String messageId = service.sendEmail(SendEmailRequest.builder() + .source("from@example.com") + .toAddresses(List.of("to@example.com")) + .region("us-east-1") + .content(new EmailContent.Raw("raw MIME")) + .build()); assertNotNull(messageId); assertFalse(emailStore.scan(k -> true).isEmpty()); @@ -314,9 +390,12 @@ class SesServiceSmtpTest { void sendRawEmail_partialSuppression_relayRawCalledWithFilteredRecipients() { suppression.putSuppressedDestination("us-east-1", "suppressed@example.com", "COMPLAINT"); - service.sendRawEmail("from@example.com", - List.of("to@example.com", "suppressed@example.com"), - "raw MIME", null, null, List.of(), null, null, "us-east-1"); + service.sendEmail(SendEmailRequest.builder() + .source("from@example.com") + .toAddresses(List.of("to@example.com", "suppressed@example.com")) + .region("us-east-1") + .content(new EmailContent.Raw("raw MIME")) + .build()); assertEquals(List.of("to@example.com"), capturedRawRelay().destinations()); } @@ -333,9 +412,13 @@ class SesServiceSmtpTest { service.createConfigurationSet(new ConfigurationSet("cs-no-suppression"), "us-east-1"); configSets.putSuppressionOptions("cs-no-suppression", List.of(), "us-east-1"); - service.sendEmail("from@example.com", - List.of("to@example.com"), null, null, null, null, - "Subject", "text body", null, "cs-no-suppression", List.of(), List.of(), null, null, "us-east-1"); + service.sendEmail(SendEmailRequest.builder() + .source("from@example.com") + .toAddresses(List.of("to@example.com")) + .configurationSetName("cs-no-suppression") + .region("us-east-1") + .content(new EmailContent.Simple("Subject", "text body", null, List.of())) + .build()); assertEquals(List.of("to@example.com"), capturedRelay().to()); } @@ -349,9 +432,13 @@ class SesServiceSmtpTest { service.createConfigurationSet(new ConfigurationSet("cs-bounce-only"), "us-east-1"); configSets.putSuppressionOptions("cs-bounce-only", List.of("BOUNCE"), "us-east-1"); - service.sendEmail("from@example.com", - List.of("complainer@example.com"), null, null, null, null, - "Subject", "text body", null, "cs-bounce-only", List.of(), List.of(), null, null, "us-east-1"); + service.sendEmail(SendEmailRequest.builder() + .source("from@example.com") + .toAddresses(List.of("complainer@example.com")) + .configurationSetName("cs-bounce-only") + .region("us-east-1") + .content(new EmailContent.Simple("Subject", "text body", null, List.of())) + .build()); assertEquals(List.of("complainer@example.com"), capturedRelay().to()); } @@ -364,9 +451,13 @@ class SesServiceSmtpTest { suppression.putSuppressedDestination("us-east-1", "to@example.com", "BOUNCE"); service.createConfigurationSet(new ConfigurationSet("cs-default"), "us-east-1"); - service.sendEmail("from@example.com", - List.of("to@example.com"), null, null, null, null, - "Subject", "text body", null, "cs-default", List.of(), List.of(), null, null, "us-east-1"); + service.sendEmail(SendEmailRequest.builder() + .source("from@example.com") + .toAddresses(List.of("to@example.com")) + .configurationSetName("cs-default") + .region("us-east-1") + .content(new EmailContent.Simple("Subject", "text body", null, List.of())) + .build()); verify(smtpRelay, never()).relay(any(SmtpRelay.RelayMessage.class)); } @@ -377,9 +468,13 @@ class SesServiceSmtpTest { service.createConfigurationSet(new ConfigurationSet("cs-no-suppression-raw"), "us-east-1"); configSets.putSuppressionOptions("cs-no-suppression-raw", List.of(), "us-east-1"); - service.sendRawEmail("from@example.com", - List.of("to@example.com"), "raw MIME", null, "cs-no-suppression-raw", List.of(), null, null, - "us-east-1"); + service.sendEmail(SendEmailRequest.builder() + .source("from@example.com") + .toAddresses(List.of("to@example.com")) + .configurationSetName("cs-no-suppression-raw") + .region("us-east-1") + .content(new EmailContent.Raw("raw MIME")) + .build()); assertEquals(List.of("to@example.com"), capturedRawRelay().destinations()); } diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/model/EmailContentTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/model/EmailContentTest.java new file mode 100644 index 0000000000..f59d6fcfb8 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/model/EmailContentTest.java @@ -0,0 +1,52 @@ +package io.github.hectorvent.floci.services.ses.model; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class EmailContentTest { + + @Test + void withSafeHeaders_dropsUnsafeHeadersAndKeepsTheRestInOrder() { + EmailContent.Simple content = new EmailContent.Simple("Subject", "text", "

html

", List.of( + new MessageHeader("X-First", "one"), + new MessageHeader(" ", "blank name"), + new MessageHeader("X-Injected\r\nBcc", "value"), + new MessageHeader("X-Split", "line\nBcc: victim@example.com"), + new MessageHeader("X-Null", null), + new MessageHeader("X-Second", "two"))); + + EmailContent.Simple safe = content.withSafeHeaders(); + + assertEquals(new EmailContent.Simple("Subject", "text", "

html

", List.of( + new MessageHeader("X-First", "one"), + new MessageHeader("X-Second", "two"))), safe); + } + + @Test + void withSafeHeaders_nullHeaders_returnsTheSameContent() { + EmailContent.Simple content = new EmailContent.Simple("Subject", "text", null, null); + + assertSame(content, content.withSafeHeaders()); + } + + @Test + void withSafeHeaders_emptyHeaders_returnsTheSameContent() { + EmailContent.Simple content = new EmailContent.Simple("Subject", "text", null, List.of()); + + assertSame(content, content.withSafeHeaders()); + } + + @Test + void hasHeaders_falseForNullOrEmptyAndTrueOtherwise() { + assertFalse(new EmailContent.Simple("Subject", "text", null, null).hasHeaders()); + assertFalse(new EmailContent.Simple("Subject", "text", null, List.of()).hasHeaders()); + assertTrue(new EmailContent.Simple("Subject", "text", null, + List.of(new MessageHeader("X-Header", "value"))).hasHeaders()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/model/SendEmailRequestTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/model/SendEmailRequestTest.java new file mode 100644 index 0000000000..079429e93c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/model/SendEmailRequestTest.java @@ -0,0 +1,93 @@ +package io.github.hectorvent.floci.services.ses.model; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.RecordComponent; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +class SendEmailRequestTest { + + // Iterates the record components so a field added to the record but not to toBuilder() fails + // here instead of silently resetting to its default whenever SesService rebuilds the request + // around rendered or sanitized content. + @Test + void toBuilderCopiesEveryComponent() throws Exception { + SendEmailRequest.Builder builder = SendEmailRequest.builder(); + for (RecordComponent component : SendEmailRequest.class.getRecordComponents()) { + Method setter = SendEmailRequest.Builder.class.getMethod(component.getName(), component.getType()); + setter.invoke(builder, sampleValue(component)); + } + SendEmailRequest original = builder.build(); + SendEmailRequest defaults = SendEmailRequest.builder().content(new EmailContent.Raw("raw")).build(); + for (RecordComponent component : SendEmailRequest.class.getRecordComponents()) { + assertNotEquals(component.getAccessor().invoke(defaults), component.getAccessor().invoke(original), + component.getName() + " must differ from its default for the round trip to prove anything"); + } + + assertEquals(original, original.toBuilder().build()); + } + + @Test + void buildWithoutContent_fails() { + NullPointerException e = assertThrows(NullPointerException.class, + () -> SendEmailRequest.builder().source("from@example.com").build()); + assertEquals("content", e.getMessage()); + } + + @Test + void recipients_concatenatesToCcBccAndSkipsNullLists() { + SendEmailRequest request = SendEmailRequest.builder() + .toAddresses(List.of("to@example.com")) + .ccAddresses(null) + .bccAddresses(List.of("bcc1@example.com", "bcc2@example.com")) + .content(new EmailContent.Raw("raw")) + .build(); + + assertEquals(List.of("to@example.com", "bcc1@example.com", "bcc2@example.com"), request.recipients()); + assertTrue(request.hasRecipients()); + } + + @Test + void hasRecipients_falseWhenEveryListIsNullOrEmpty() { + SendEmailRequest request = SendEmailRequest.builder() + .toAddresses(null) + .ccAddresses(List.of()) + .bccAddresses(null) + .content(new EmailContent.Raw("raw")) + .build(); + + assertEquals(List.of(), request.recipients()); + assertFalse(request.hasRecipients()); + } + + private static Object sampleValue(RecordComponent component) { + if (component.getType() == String.class) { + return component.getName() + "-value"; + } + if (component.getType() == ListManagementOptions.class) { + return new ListManagementOptions("list", "topic"); + } + if (component.getType() == EmailContent.class) { + return new EmailContent.Simple("subject", "text", "

html

", List.of()); + } + if (component.getType() == List.class) { + Object element = ((ParameterizedType) component.getGenericType()).getActualTypeArguments()[0]; + if (element == String.class) { + return List.of(component.getName() + "@example.com"); + } + if (element == MessageTag.class) { + return List.of(new MessageTag("tag", "value")); + } + } + return fail("no sample value for component " + component.getName() + " of type " + component.getGenericType()); + } +}