mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(ses): preserve raw message fidelity and envelope sender in the SMTP relay (#3522)
* feat(ses): preserve raw messages, envelope sender, and X-SES headers in SMTP relay
The raw relay reparsed each MIME message and rebuilt it from the text and
HTML parts alone, dropping every attachment and custom header. It now walks
the Mime4j tree and maps it onto the outgoing message: the first text/plain
and text/html parts become the body, every other leaf becomes an attachment
(inline when it carries a Content-ID, so cid: references still resolve), an
embedded message/rfc822 part is relayed whole, and display names on addresses
survive. Top-level headers are copied through apart from the MIME structural
ones, which the encoder regenerates for the re-built message.
Wire the envelope sender through to MAIL FROM, resolved in AWS's order: the
Return-Path MIME header, then the ReturnPath request field (v1) or
FeedbackForwardingEmailAddress (v2), then the source. The resolved value is
recorded on SentEmail so the inspection endpoint shows it.
Stamp relayed messages with <{MessageId}@{region}.amazonses.com>, matching the
MessageId returned to the caller, leaving a caller-supplied Message-ID alone.
Honour the X-SES-CONFIGURATION-SET and X-SES-MESSAGE-TAGS control headers on
raw sends, which previously parsed to nothing and left event publishing
silently inert for callers using the header form. Both are stripped from the
relayed message, as AWS consumes rather than forwards them. The tenant send
gate sees the same resolved configuration set, so one named only by header
cannot slip past the association check.
Fix tryBase64Decode, which decoded every raw message with the MIME decoder and
only fell back to plain text when it threw. That decoder skips characters
outside the base64 alphabet rather than rejecting them, so a plain-text RFC
5322 message decoded into garbage whenever the surviving alphabet characters
happened to form a valid length, wiping its headers. The alphabet is now
checked before decoding.
Replace the nine-argument SmtpRelay.relay with a RelayMessage record, and add
a ServerSocket-based SMTP test that drives a real MailClient end to end and
asserts on the negotiated envelope and the bytes on the wire, covering the
authentication and STARTTLS-OPTIONAL configuration branches.
* fix(ses): align SMTP relay with documented AWS header and tag semantics
Verified the relay against the SES documentation and corrected four
deviations.
AWS overrides a caller-supplied Message-ID with the id it assigned, and
rejects Message-ID outright as a custom header on Simple and Templated
content (SES header fields reference). The relay preserved a caller's value
instead; it now always stamps the id returned by the API.
AWS likewise overrides a caller-supplied Date with the time it accepted the
message. The relay copied the caller's Date through, so a stale timestamp
reached the recipient. Date is now regenerated with the rest of the headers
SES sets.
AWS uses only the request field's message tags when tags are supplied both
as a request field and as an X-SES-MESSAGE-TAGS header, and explicitly does
not join the two sets. The relay merged them, letting a header-only tag
survive a request that supplied its own. Header tags now apply only when the
request passes none.
The stamped Message-ID domain was region-scoped, which no AWS documentation
or observed output supports. Use the observed email.amazonses.com instead,
and record in the docs that only the local part, which is the returned
MessageId, is documented behaviour.
Also document that AWS delivers a Return-Path differing from the one
supplied, because it routes bounces through its own address, whereas Floci
has no bounce pipeline and puts the resolved address directly in MAIL FROM.
* fix(ses): align mime4j artifacts to unbreak the native build
The raw relay's new DefaultMessageWriter path failed GraalVM analysis with
an unresolved reference to Field.getSafeRaw(). apache-mime4j-dom was pinned
to 0.8.14 while the Quarkus BOM manages apache-mime4j-core at 0.8.12, so the
writer was compiled against a Field API the resolved core does not declare.
Nothing reached the writer before this branch, which is why the skew only
surfaced now, and only in native builds.
Drop the hardcoded -dom version so both artifacts track the BOM together,
and cover the embedded message/rfc822 branch that exercises the writer.
This commit is contained in:
1 parent
325bdfb30e
commit
505b5d286e
17 files changed
+1790
-266
No files matched your search
+98
-9
@@ -93,10 +93,13 @@ Floci exposes the classic Amazon SES Query API used by `aws ses ...` commands an
|
||||
|
||||
### SMTP Relay
|
||||
|
||||
When `smtp-host` is configured, `SendEmail` and `SendRawEmail` forward
|
||||
emails to the specified SMTP server in addition to storing them in the
|
||||
local inspection endpoint. This enables integration testing with tools
|
||||
like [Mailpit](https://mailpit.axllent.org/) or any standard SMTP server.
|
||||
When `smtp-host` is configured, every send operation forwards the email
|
||||
to the specified SMTP server in addition to storing it in the local
|
||||
inspection endpoint: `SendEmail` (simple, raw, and templated content),
|
||||
`SendRawEmail`, `SendTemplatedEmail`, `SendBulkTemplatedEmail`,
|
||||
`SendBulkEmail`, and `SendCustomVerificationEmail`. This enables
|
||||
integration testing with tools like
|
||||
[Mailpit](https://mailpit.axllent.org/) or any standard SMTP server.
|
||||
|
||||
```yaml
|
||||
# docker-compose.yml
|
||||
@@ -120,13 +123,95 @@ networks:
|
||||
floci:
|
||||
```
|
||||
|
||||
- Emails are always stored locally regardless of relay — the
|
||||
- Emails are always stored locally regardless of relay: the
|
||||
`/_aws/ses` inspection endpoint works with or without SMTP.
|
||||
- Relay failures are logged but do not affect the API response.
|
||||
- Raw MIME messages are parsed with Apache Mime4j to extract common
|
||||
fields (From, To, Cc, Subject, text/plain and text/html parts) and
|
||||
relayed as a reconstructed message. Arbitrary headers, attachments,
|
||||
and complex multipart structures are not preserved in the relay.
|
||||
- Recipients on the suppression list are filtered out before the relay.
|
||||
A send whose recipients are all suppressed is still stored, but never
|
||||
reaches the SMTP server.
|
||||
|
||||
#### Raw message fidelity
|
||||
|
||||
Raw MIME messages are parsed with Apache Mime4j and relayed as a
|
||||
re-encoded message that preserves the original content:
|
||||
|
||||
- The first `text/plain` and `text/html` parts become the message body.
|
||||
- Attachments are preserved with their filename, content type,
|
||||
disposition, and description. Parts carrying a `Content-ID` are
|
||||
relayed as inline attachments, so `cid:` references in an HTML body
|
||||
still resolve. An embedded `message/rfc822` part is relayed whole.
|
||||
- Custom top-level headers are copied through. The MIME structural
|
||||
headers (`MIME-Version`, `Content-Type`, `Content-Transfer-Encoding`)
|
||||
are regenerated for the re-encoded message, and the address, subject,
|
||||
and `Return-Path` headers are applied to the outgoing message
|
||||
directly rather than copied.
|
||||
- `Date` and `Message-ID` are replaced rather than copied, matching the
|
||||
[SES header fields reference](https://docs.aws.amazon.com/ses/latest/dg/header-fields.html):
|
||||
AWS overrides a caller's `Date` with the time it accepted the message,
|
||||
and a caller's `Message-ID` with the id it assigned.
|
||||
- Display names on addresses are kept, so
|
||||
`Alice <alice@example.com>` is delivered as written. The bare
|
||||
addresses are what the SMTP envelope, the suppression checks, and the
|
||||
published events use.
|
||||
- `RawMessage.Data` / `Content.Raw.Data` is accepted either
|
||||
base64-encoded (what the AWS SDKs send) or as plain RFC 5322 text.
|
||||
|
||||
#### Envelope sender
|
||||
|
||||
AWS routes bounce and complaint notifications to the address in the
|
||||
`Return-Path` header. Floci resolves that address in the order:
|
||||
|
||||
1. The `Return-Path` header on a raw MIME message
|
||||
2. The `ReturnPath` request field (v1) or
|
||||
`FeedbackForwardingEmailAddress` (v2)
|
||||
3. The source address
|
||||
|
||||
The resolved value is used as the SMTP `MAIL FROM` address, which is
|
||||
where a receiving mail server routes bounces, and is recorded as
|
||||
`ReturnPath` on the stored message so the inspection endpoint shows it.
|
||||
|
||||
!!! note "Deviations"
|
||||
On AWS the delivered message carries a `Return-Path` that differs
|
||||
from the one you supplied, because AWS routes bounces through its
|
||||
own address and forwards them on. Floci has no bounce-handling
|
||||
pipeline, so it puts the resolved address directly in `MAIL FROM`
|
||||
instead, which is the closest local equivalent.
|
||||
|
||||
Floci also does not deliver bounce and complaint notifications to
|
||||
the return path at all. Notification targets are resolved from the
|
||||
identity (`SetIdentityNotificationTopic`) and from the configuration
|
||||
set's event destinations instead.
|
||||
|
||||
#### Message-ID
|
||||
|
||||
AWS overrides any caller-supplied `Message-ID` with the id it assigned,
|
||||
which is the `MessageId` returned by the API. Floci does the same,
|
||||
stamping `<{MessageId}@email.amazonses.com>`.
|
||||
|
||||
!!! note
|
||||
The local part is the returned `MessageId`, which is the documented
|
||||
part of this behaviour. The `email.amazonses.com` domain is not
|
||||
specified in the AWS documentation and follows observed SES output.
|
||||
|
||||
#### X-SES control headers
|
||||
|
||||
On a raw send, Floci honours the SES control headers and strips them
|
||||
from the relayed message rather than forwarding them:
|
||||
|
||||
| Header | Effect |
|
||||
|---|---|
|
||||
| `X-SES-CONFIGURATION-SET` | Names the configuration set to apply when the request does not specify one |
|
||||
| `X-SES-MESSAGE-TAGS` | Comma-separated `name=value` message tags, used for event publishing |
|
||||
|
||||
Per
|
||||
[Step 3: Specify your configuration set](https://docs.aws.amazon.com/ses/latest/dg/event-publishing-send-email.html),
|
||||
when message tags are supplied both as a request field and as a header,
|
||||
AWS uses only the request field's tags and does not join the two sets.
|
||||
Floci matches this: header tags apply only when the request passes none.
|
||||
|
||||
All other `X-SES-*` headers, including the sending-authorization headers
|
||||
`X-SES-SOURCE-ARN`, `X-SES-FROM-ARN`, and `X-SES-RETURN-PATH-ARN`, are
|
||||
stripped from the relayed message without being acted on.
|
||||
|
||||
## Local Inspection Endpoint
|
||||
|
||||
@@ -138,6 +223,10 @@ For test assertions and debugging, Floci exposes a LocalStack-compatible mailbox
|
||||
|
||||
Messages are stored locally by Floci and can be persisted when SES storage is backed by persistent or hybrid storage.
|
||||
|
||||
Alongside the LocalStack fields, each captured message carries a
|
||||
`ReturnPath` holding the resolved envelope sender described under
|
||||
[SMTP Relay](#smtp-relay).
|
||||
|
||||
## Examples
|
||||
|
||||
```bash
|
||||
|
||||
@@ -131,7 +131,6 @@
|
||||
<dependency>
|
||||
<groupId>org.apache.james</groupId>
|
||||
<artifactId>apache-mime4j-dom</artifactId>
|
||||
<version>0.8.14</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Jackson for JSON storage serialization -->
|
||||
|
||||
+1
@@ -71,6 +71,7 @@ public final class CognitoMessageDispatcher {
|
||||
DEFAULT_FROM,
|
||||
List.of(email),
|
||||
List.of(), List.of(), List.of(),
|
||||
null, // returnPath
|
||||
subject,
|
||||
body,
|
||||
null, // bodyHtml
|
||||
|
||||
@@ -479,6 +479,8 @@ public class SesController {
|
||||
List<String> ccAddresses = jsonArrayToList(destination.path("CcAddresses"));
|
||||
List<String> bccAddresses = jsonArrayToList(destination.path("BccAddresses"));
|
||||
List<String> replyToAddresses = jsonArrayToList(request.path("ReplyToAddresses"));
|
||||
String feedbackForwardingAddress =
|
||||
request.path("FeedbackForwardingEmailAddress").asText(null);
|
||||
List<String> allDestinations = mergeLists(toAddresses, ccAddresses, bccAddresses);
|
||||
String configurationSetName = request.path("ConfigurationSetName").asText(null);
|
||||
String tenantName = stringMemberOrAbsent(request, "TenantName");
|
||||
@@ -502,7 +504,8 @@ public class SesController {
|
||||
sesService.checkTenantRawSendAccess(tenantName, fromEmailAddress, rawData,
|
||||
configurationSetName, regionResolver.getAccountId(), region);
|
||||
messageId = sesService.sendRawEmail(fromEmailAddress, allDestinations, rawData,
|
||||
configurationSetName, emailTags, listManagement, region);
|
||||
feedbackForwardingAddress, configurationSetName, emailTags, listManagement,
|
||||
region);
|
||||
} else if (content.has("Simple")) {
|
||||
if (fromEmailAddress == null || fromEmailAddress.isBlank()) {
|
||||
// AWS returns BadRequestException with a null message body here.
|
||||
@@ -517,7 +520,8 @@ public class SesController {
|
||||
sesService.checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName,
|
||||
null, regionResolver.getAccountId(), region);
|
||||
messageId = sesService.sendEmail(fromEmailAddress, toAddresses, ccAddresses,
|
||||
bccAddresses, replyToAddresses, subject, bodyText, bodyHtml,
|
||||
bccAddresses, replyToAddresses, feedbackForwardingAddress,
|
||||
subject, bodyText, bodyHtml,
|
||||
configurationSetName, emailTags, additionalHeaders, listManagement, region);
|
||||
} else if (content.has("Template")) {
|
||||
if (fromEmailAddress == null || fromEmailAddress.isBlank()) {
|
||||
@@ -549,7 +553,8 @@ public class SesController {
|
||||
sesService.checkTenantSendAccess(tenantName, fromEmailAddress,
|
||||
configurationSetName, resolvedName, regionResolver.getAccountId(), region);
|
||||
messageId = sesService.sendTemplatedEmail(fromEmailAddress, toAddresses, ccAddresses,
|
||||
bccAddresses, replyToAddresses, resolvedName, templateData,
|
||||
bccAddresses, replyToAddresses, feedbackForwardingAddress,
|
||||
resolvedName, templateData,
|
||||
configurationSetName, emailTags, additionalHeaders, listManagement, region);
|
||||
} else {
|
||||
JsonNode inline = template.path("TemplateContent");
|
||||
@@ -563,7 +568,7 @@ public class SesController {
|
||||
sesService.checkTenantSendAccess(tenantName, fromEmailAddress,
|
||||
configurationSetName, null, regionResolver.getAccountId(), region);
|
||||
messageId = sesService.sendInlineTemplatedEmail(fromEmailAddress, toAddresses,
|
||||
ccAddresses, bccAddresses, replyToAddresses,
|
||||
ccAddresses, bccAddresses, replyToAddresses, feedbackForwardingAddress,
|
||||
subject, text, html, templateData,
|
||||
configurationSetName, emailTags, additionalHeaders, listManagement, region);
|
||||
}
|
||||
@@ -603,6 +608,8 @@ public class SesController {
|
||||
"FromEmailAddress is required.", 400);
|
||||
}
|
||||
List<String> replyToAddresses = jsonArrayToList(request.path("ReplyToAddresses"));
|
||||
String feedbackForwardingAddress =
|
||||
request.path("FeedbackForwardingEmailAddress").asText(null);
|
||||
String configurationSetName = request.path("ConfigurationSetName").asText(null);
|
||||
String tenantName = stringMemberOrAbsent(request, "TenantName");
|
||||
|
||||
@@ -689,7 +696,7 @@ public class SesController {
|
||||
gateTemplateName, regionResolver.getAccountId(), region);
|
||||
|
||||
List<BulkEmailEntryResult> results = sesService.sendBulkTemplatedEmail(fromEmailAddress,
|
||||
replyToAddresses, subject, text, html,
|
||||
replyToAddresses, feedbackForwardingAddress, subject, text, html,
|
||||
defaultTemplateData, entries, configurationSetName,
|
||||
defaultEmailTags, defaultHeaders, region);
|
||||
|
||||
|
||||
@@ -54,6 +54,9 @@ public class SesInspectionController {
|
||||
node.putNull("Region");
|
||||
}
|
||||
node.put("Source", email.getSource());
|
||||
if (email.getReturnPath() != null) {
|
||||
node.put("ReturnPath", email.getReturnPath());
|
||||
}
|
||||
|
||||
if (email.isRaw()) {
|
||||
// LocalStack returns RawData for raw emails, without
|
||||
|
||||
@@ -226,11 +226,12 @@ public class SesQueryHandler {
|
||||
String bodyText = getParam(params, "Message.Body.Text.Data");
|
||||
String bodyHtml = getParam(params, "Message.Body.Html.Data");
|
||||
String configurationSetName = getParam(params, "ConfigurationSetName");
|
||||
String returnPath = getParam(params, "ReturnPath");
|
||||
List<MessageTag> 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, subject, bodyText, bodyHtml, configurationSetName,
|
||||
replyToAddresses, returnPath, subject, bodyText, bodyHtml, configurationSetName,
|
||||
emailTags, List.of(), null, region);
|
||||
|
||||
String result = new XmlBuilder().elem("MessageId", messageId).build();
|
||||
@@ -249,7 +250,7 @@ public class SesQueryHandler {
|
||||
List<MessageTag> emailTags = extractMessageTags(params, "Tags");
|
||||
|
||||
String messageId = sesService.sendRawEmail(source, destinations, rawMessage,
|
||||
configurationSetName, emailTags, null, region);
|
||||
null, configurationSetName, emailTags, null, region);
|
||||
|
||||
String result = new XmlBuilder().elem("MessageId", messageId).build();
|
||||
return Response.ok(AwsQueryResponse.envelope("SendRawEmail", AwsNamespaces.SES, result)).build();
|
||||
@@ -573,9 +574,10 @@ public class SesQueryHandler {
|
||||
|
||||
JsonNode templateData = parseTemplateData(templateDataRaw);
|
||||
String configurationSetName = getParam(params, "ConfigurationSetName");
|
||||
String returnPath = getParam(params, "ReturnPath");
|
||||
List<MessageTag> emailTags = extractMessageTags(params, "Tags");
|
||||
String messageId = sesService.sendTemplatedEmail(source, toAddresses, ccAddresses,
|
||||
bccAddresses, replyToAddresses, resolvedName, templateData,
|
||||
bccAddresses, replyToAddresses, returnPath, resolvedName, templateData,
|
||||
configurationSetName, emailTags, List.of(), null, region);
|
||||
|
||||
String result = new XmlBuilder().elem("MessageId", messageId).build();
|
||||
@@ -715,9 +717,10 @@ public class SesQueryHandler {
|
||||
}
|
||||
|
||||
String configurationSetName = getParam(params, "ConfigurationSetName");
|
||||
String returnPath = getParam(params, "ReturnPath");
|
||||
List<MessageTag> defaultEmailTags = extractMessageTags(params, "DefaultTags");
|
||||
List<BulkEmailEntryResult> results = sesService.sendBulkTemplatedEmail(source, replyToAddresses,
|
||||
template.getSubject(), template.getTextPart(), template.getHtmlPart(),
|
||||
returnPath, template.getSubject(), template.getTextPart(), template.getHtmlPart(),
|
||||
defaultTemplateData, entries, configurationSetName,
|
||||
defaultEmailTags, List.of(), region);
|
||||
|
||||
|
||||
@@ -218,7 +218,7 @@ public class SesService {
|
||||
}
|
||||
|
||||
public String sendEmail(String source, List<String> toAddresses, List<String> ccAddresses,
|
||||
List<String> bccAddresses, List<String> replyToAddresses,
|
||||
List<String> bccAddresses, List<String> replyToAddresses, String returnPath,
|
||||
String subject, String bodyText, String bodyHtml,
|
||||
String configurationSetName, List<MessageTag> emailTags,
|
||||
List<MessageHeader> additionalHeaders, ListManagementOptions listManagement,
|
||||
@@ -264,8 +264,10 @@ public class SesService {
|
||||
}
|
||||
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
String effectiveReturnPath = firstNonBlank(returnPath, source);
|
||||
SentEmail email = new SentEmail(messageId, region, source, toAddresses, ccAddresses,
|
||||
bccAddresses, replyToAddresses, subject, bodyText, bodyHtml);
|
||||
email.setReturnPath(effectiveReturnPath);
|
||||
if (additionalHeaders != null && !additionalHeaders.isEmpty()) {
|
||||
email.setHeaders(additionalHeaders);
|
||||
}
|
||||
@@ -275,8 +277,18 @@ public class SesService {
|
||||
List<String> relayedCc = filterUnsuppressed(ccAddresses, suppressedReasons);
|
||||
List<String> relayedBcc = filterUnsuppressed(bccAddresses, suppressedReasons);
|
||||
if (sizeOf(relayedTo) + sizeOf(relayedCc) + sizeOf(relayedBcc) > 0) {
|
||||
smtpRelay.relay(source, relayedTo, relayedCc, relayedBcc,
|
||||
replyToAddresses, subject, bodyText, bodyHtml, additionalHeaders);
|
||||
smtpRelay.relay(SmtpRelay.RelayMessage.builder(source)
|
||||
.returnPath(effectiveReturnPath)
|
||||
.to(relayedTo)
|
||||
.cc(relayedCc)
|
||||
.bcc(relayedBcc)
|
||||
.replyTo(replyToAddresses)
|
||||
.subject(subject)
|
||||
.bodyText(bodyText)
|
||||
.bodyHtml(bodyHtml)
|
||||
.headers(additionalHeaders)
|
||||
.messageId(messageId)
|
||||
.build());
|
||||
} else {
|
||||
LOG.infov("SES email accepted but not relayed (all recipients suppressed): messageId={0}",
|
||||
messageId);
|
||||
@@ -291,21 +303,29 @@ public class SesService {
|
||||
}
|
||||
|
||||
public String sendRawEmail(String source, List<String> destinations, String rawMessage,
|
||||
String configurationSetName, List<MessageTag> emailTags,
|
||||
String returnPath, String configurationSetName, List<MessageTag> emailTags,
|
||||
ListManagementOptions listManagement, String region) {
|
||||
if (rawMessage == null || rawMessage.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "RawMessage.Data is required.", 400);
|
||||
}
|
||||
String effectiveConfigSet = resolveDefaultConfigurationSet(configurationSetName, source, region);
|
||||
configSetService.validateForSending(effectiveConfigSet, region);
|
||||
boolean hasExplicitDestinations = destinations != null && !destinations.isEmpty();
|
||||
boolean sourceOmitted = source == null || source.isBlank();
|
||||
boolean willPublishEvents = (effectiveConfigSet != null && !effectiveConfigSet.isBlank())
|
||||
|| !resolveIdentityNotificationTargets(source, region).isEmpty();
|
||||
SmtpRelay.RawMessageHeaders headers = (hasExplicitDestinations && !willPublishEvents && !sourceOmitted)
|
||||
? null
|
||||
: SmtpRelay.parseRawHeaders(rawMessage);
|
||||
String effectiveSource = sourceOmitted && headers != null && !headers.from().isBlank()
|
||||
// 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.RawMessageHeaders headers = SmtpRelay.parseRawHeaders(rawMessage);
|
||||
// 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 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<MessageTag> effectiveTags = (emailTags == null || emailTags.isEmpty())
|
||||
? headers.messageTags()
|
||||
: emailTags;
|
||||
String effectiveSource = sourceOmitted && !headers.from().isBlank()
|
||||
? headers.from()
|
||||
: source;
|
||||
if (effectiveSource == null || effectiveSource.isBlank()) {
|
||||
@@ -319,8 +339,8 @@ public class SesService {
|
||||
// sender until the MIME "From" was parsed. Re-resolve from the effective sender now so an
|
||||
// email identity's default configuration set still applies to a Raw send without an
|
||||
// explicit FromEmailAddress.
|
||||
if (sourceOmitted && (configurationSetName == null || configurationSetName.isBlank())) {
|
||||
effectiveConfigSet = resolveDefaultConfigurationSet(configurationSetName, effectiveSource, region);
|
||||
if (sourceOmitted && (requestedConfigSet == null || requestedConfigSet.isBlank())) {
|
||||
effectiveConfigSet = resolveDefaultConfigurationSet(requestedConfigSet, effectiveSource, region);
|
||||
configSetService.validateForSending(effectiveConfigSet, region);
|
||||
}
|
||||
List<String> effectiveDestinations = hasExplicitDestinations
|
||||
@@ -341,12 +361,17 @@ public class SesService {
|
||||
.forEach(suppressedReasons::putIfAbsent);
|
||||
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
// AWS routes bounces to the Return-Path carried by the message, falling back to the
|
||||
// request's return path and then the sender.
|
||||
String effectiveReturnPath = firstNonBlank(headers.returnPath(), returnPath, effectiveSource);
|
||||
SentEmail email = new SentEmail(messageId, region, effectiveSource, effectiveDestinations, rawMessage);
|
||||
email.setReturnPath(effectiveReturnPath);
|
||||
sentEmailService.record(region, messageId, email);
|
||||
|
||||
List<String> relayedDestinations = filterUnsuppressed(effectiveDestinations, suppressedReasons);
|
||||
if (!relayedDestinations.isEmpty()) {
|
||||
smtpRelay.relayRaw(effectiveSource, relayedDestinations, rawMessage);
|
||||
smtpRelay.relayRaw(new SmtpRelay.RawRelayMessage(effectiveSource, effectiveReturnPath,
|
||||
relayedDestinations, rawMessage, messageId));
|
||||
} else {
|
||||
LOG.infov("SES raw email accepted but not relayed (all recipients suppressed): messageId={0}",
|
||||
messageId);
|
||||
@@ -354,12 +379,9 @@ public class SesService {
|
||||
|
||||
LOG.infov("SES raw email sent: from={0}, messageId={1}", effectiveSource, messageId);
|
||||
publishSendEvents(effectiveConfigSet, messageId, effectiveSource,
|
||||
headers != null ? headers.subject() : "",
|
||||
headers != null ? headers.to() : List.of(),
|
||||
headers != null ? headers.cc() : List.of(),
|
||||
headers != null ? headers.bcc() : List.of(),
|
||||
headers.subject(), headers.to(), headers.cc(), headers.bcc(),
|
||||
effectiveDestinations,
|
||||
suppressedReasons, emailTags, List.of(), region);
|
||||
suppressedReasons, effectiveTags, List.of(), region);
|
||||
return messageId;
|
||||
}
|
||||
|
||||
@@ -803,9 +825,19 @@ public class SesService {
|
||||
SentEmail email = new SentEmail(messageId, region, template.getFromEmailAddress(),
|
||||
List.of(emailAddress), List.of(), List.of(), List.of(),
|
||||
template.getTemplateSubject(), null, renderedHtml);
|
||||
email.setReturnPath(template.getFromEmailAddress());
|
||||
sentEmailService.record(region, messageId, email);
|
||||
smtpRelay.relay(template.getFromEmailAddress(), List.of(emailAddress), List.of(), List.of(),
|
||||
List.of(), template.getTemplateSubject(), null, renderedHtml, List.of());
|
||||
smtpRelay.relay(SmtpRelay.RelayMessage.builder(template.getFromEmailAddress())
|
||||
.returnPath(template.getFromEmailAddress())
|
||||
.to(List.of(emailAddress))
|
||||
.cc(List.of())
|
||||
.bcc(List.of())
|
||||
.replyTo(List.of())
|
||||
.subject(template.getTemplateSubject())
|
||||
.bodyHtml(renderedHtml)
|
||||
.headers(List.of())
|
||||
.messageId(messageId)
|
||||
.build());
|
||||
LOG.infov("SES custom verification email sent: to={0}, template={1}, messageId={2}",
|
||||
emailAddress, templateName, messageId);
|
||||
return messageId;
|
||||
@@ -1069,12 +1101,15 @@ public class SesService {
|
||||
if (tenantName == null) {
|
||||
return;
|
||||
}
|
||||
SmtpRelay.RawMessageHeaders headers = SmtpRelay.parseRawHeaders(rawMessage);
|
||||
String effectiveSource = fromEmailAddress;
|
||||
if (effectiveSource == null || effectiveSource.isBlank()) {
|
||||
SmtpRelay.RawMessageHeaders headers = SmtpRelay.parseRawHeaders(rawMessage);
|
||||
effectiveSource = headers != null && !headers.from().isBlank() ? headers.from() : null;
|
||||
effectiveSource = headers.from().isBlank() ? null : headers.from();
|
||||
}
|
||||
checkTenantSendAccess(tenantName, effectiveSource, configurationSetName, null,
|
||||
// The gate sees the same configuration set the send will use, so one named only by the
|
||||
// X-SES-CONFIGURATION-SET header cannot slip past the tenant association check.
|
||||
checkTenantSendAccess(tenantName, effectiveSource,
|
||||
firstNonBlank(configurationSetName, headers.configurationSet()), null,
|
||||
accountId, region);
|
||||
}
|
||||
|
||||
@@ -1780,13 +1815,13 @@ 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 returnPath, String templateName, JsonNode templateData,
|
||||
String configurationSetName, List<MessageTag> emailTags,
|
||||
List<MessageHeader> additionalHeaders,
|
||||
ListManagementOptions listManagement, String region) {
|
||||
EmailTemplate template = getTemplate(templateName, region);
|
||||
return sendInlineTemplatedEmail(source, toAddresses, ccAddresses, bccAddresses,
|
||||
replyToAddresses, template.getSubject(), template.getTextPart(),
|
||||
replyToAddresses, returnPath, template.getSubject(), template.getTextPart(),
|
||||
template.getHtmlPart(), templateData,
|
||||
configurationSetName, emailTags, additionalHeaders, listManagement, region);
|
||||
}
|
||||
@@ -1812,13 +1847,14 @@ public class SesService {
|
||||
|
||||
public String sendInlineTemplatedEmail(String source, List<String> toAddresses, List<String> ccAddresses,
|
||||
List<String> bccAddresses, List<String> replyToAddresses,
|
||||
String returnPath,
|
||||
String subject, String textPart, String htmlPart,
|
||||
JsonNode templateData,
|
||||
String configurationSetName, List<MessageTag> emailTags,
|
||||
List<MessageHeader> additionalHeaders,
|
||||
ListManagementOptions listManagement, String region) {
|
||||
requireInlineTemplateContent(subject, textPart, htmlPart);
|
||||
return sendEmail(source, toAddresses, ccAddresses, bccAddresses, replyToAddresses,
|
||||
return sendEmail(source, toAddresses, ccAddresses, bccAddresses, replyToAddresses, returnPath,
|
||||
SesTemplateService.applyTemplateData(subject, templateData),
|
||||
SesTemplateService.applyTemplateData(textPart, templateData),
|
||||
SesTemplateService.applyTemplateData(htmlPart, templateData),
|
||||
@@ -1827,6 +1863,7 @@ public class SesService {
|
||||
|
||||
public List<BulkEmailEntryResult> sendBulkTemplatedEmail(String source,
|
||||
List<String> replyToAddresses,
|
||||
String returnPath,
|
||||
String subject, String textPart, String htmlPart,
|
||||
JsonNode defaultTemplateData,
|
||||
List<BulkEmailEntry> entries,
|
||||
@@ -1869,7 +1906,7 @@ public class SesService {
|
||||
// does not apply to bulk sends.
|
||||
String messageId = sendEmail(source,
|
||||
entry.toAddresses(), entry.ccAddresses(), entry.bccAddresses(),
|
||||
replyToAddresses,
|
||||
replyToAddresses, returnPath,
|
||||
SesTemplateService.applyTemplateData(subject, merged),
|
||||
SesTemplateService.applyTemplateData(textPart, merged),
|
||||
SesTemplateService.applyTemplateData(htmlPart, merged),
|
||||
@@ -1889,6 +1926,15 @@ public class SesService {
|
||||
return list == null ? 0 : list.size();
|
||||
}
|
||||
|
||||
private static String firstNonBlank(String... values) {
|
||||
for (String value : values) {
|
||||
if (value != null && !value.isBlank()) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static BulkEmailEntryResult.Status mapErrorCodeToBulkStatus(String errorCode) {
|
||||
if ("InvalidParameterValue".equals(errorCode)
|
||||
|| "MissingRenderingAttribute".equals(errorCode)
|
||||
|
||||
@@ -2,6 +2,9 @@ package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
|
||||
import io.github.hectorvent.floci.services.ses.model.MessageTag;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.ext.mail.MailAttachment;
|
||||
import io.vertx.ext.mail.MailClient;
|
||||
import io.vertx.ext.mail.MailConfig;
|
||||
import io.vertx.ext.mail.MailMessage;
|
||||
@@ -11,19 +14,30 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.apache.james.mime4j.dom.Body;
|
||||
import org.apache.james.mime4j.dom.Entity;
|
||||
import org.apache.james.mime4j.dom.Header;
|
||||
import org.apache.james.mime4j.dom.Message;
|
||||
import org.apache.james.mime4j.dom.Multipart;
|
||||
import org.apache.james.mime4j.dom.SingleBody;
|
||||
import org.apache.james.mime4j.dom.TextBody;
|
||||
import org.apache.james.mime4j.dom.address.Mailbox;
|
||||
import org.apache.james.mime4j.dom.address.MailboxList;
|
||||
import org.apache.james.mime4j.dom.field.FieldName;
|
||||
import org.apache.james.mime4j.field.address.AddressFormatter;
|
||||
import org.apache.james.mime4j.message.DefaultMessageBuilder;
|
||||
import org.apache.james.mime4j.message.DefaultMessageWriter;
|
||||
import org.apache.james.mime4j.stream.Field;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.AbstractExecutorService;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -44,6 +58,31 @@ public class SmtpRelay {
|
||||
private static final Logger LOG = Logger.getLogger(SmtpRelay.class);
|
||||
private static final long RELAY_TIMEOUT_SECONDS = 30;
|
||||
|
||||
/** SES control header naming the configuration set to apply to a raw send. */
|
||||
public static final String HEADER_CONFIGURATION_SET = "X-SES-CONFIGURATION-SET";
|
||||
/** SES control header carrying {@code name=value} message tags for a raw send. */
|
||||
public static final String HEADER_MESSAGE_TAGS = "X-SES-MESSAGE-TAGS";
|
||||
|
||||
private static final String X_SES_PREFIX = "x-ses-";
|
||||
private static final String HEADER_RETURN_PATH = "Return-Path";
|
||||
private static final String MESSAGE_ID_DOMAIN = "email.amazonses.com";
|
||||
|
||||
/**
|
||||
* Top-level headers of a raw message that are not copied onto the relayed message. The MIME
|
||||
* structural headers are regenerated by the Vert.x encoder for the re-built message, so passing
|
||||
* the originals through would announce a content type and boundary that no longer describe the
|
||||
* body. The address and subject headers are set on {@link MailMessage} directly, and
|
||||
* {@code Return-Path} becomes the envelope sender (the receiving MTA writes its own).
|
||||
*
|
||||
* <p>{@code Date} and {@code Message-ID} are excluded because AWS overrides both: a caller's
|
||||
* {@code Date} is replaced with the time the message was accepted, and a caller's
|
||||
* {@code Message-ID} with the id SES assigned (SES header fields reference).
|
||||
*/
|
||||
private static final Set<String> SUPPRESSED_RELAY_HEADERS = Set.of(
|
||||
"mime-version", "content-type", "content-transfer-encoding",
|
||||
"content-disposition", "content-id",
|
||||
"from", "to", "cc", "bcc", "subject", "return-path", "message-id", "date");
|
||||
|
||||
private final MailClient mailClient;
|
||||
private final ExecutorService relayExecutor;
|
||||
private final boolean enabled;
|
||||
@@ -64,35 +103,39 @@ public class SmtpRelay {
|
||||
int port = config.services().ses().smtpPort();
|
||||
LOG.infov("SES SMTP relay enabled: {0}:{1}", host, String.valueOf(port));
|
||||
|
||||
MailConfig mailConfig = new MailConfig()
|
||||
.setHostname(host)
|
||||
.setPort(port);
|
||||
config.services().ses().smtpUser()
|
||||
.filter(u -> !u.isBlank())
|
||||
.ifPresent(u -> {
|
||||
mailConfig.setUsername(u);
|
||||
config.services().ses().smtpPass()
|
||||
.filter(p -> !p.isBlank())
|
||||
.ifPresent(mailConfig::setPassword);
|
||||
});
|
||||
String starttls = config.services().ses().smtpStarttls();
|
||||
if ("REQUIRED".equalsIgnoreCase(starttls)) {
|
||||
mailConfig.setStarttls(StartTLSOptions.REQUIRED);
|
||||
} else if ("OPTIONAL".equalsIgnoreCase(starttls)) {
|
||||
mailConfig.setStarttls(StartTLSOptions.OPTIONAL);
|
||||
} else {
|
||||
if (!"DISABLED".equalsIgnoreCase(starttls)) {
|
||||
LOG.warnv("Unrecognized smtp-starttls value \"{0}\", defaulting to DISABLED", starttls);
|
||||
}
|
||||
mailConfig.setStarttls(StartTLSOptions.DISABLED);
|
||||
}
|
||||
this.mailClient = MailClient.create(vertx, mailConfig);
|
||||
this.mailClient = MailClient.create(vertx, buildMailConfig(config, host, port));
|
||||
} else {
|
||||
this.relayExecutor = null;
|
||||
this.mailClient = null;
|
||||
}
|
||||
}
|
||||
|
||||
static MailConfig buildMailConfig(EmulatorConfig config, String host, int port) {
|
||||
MailConfig mailConfig = new MailConfig()
|
||||
.setHostname(host)
|
||||
.setPort(port);
|
||||
config.services().ses().smtpUser()
|
||||
.filter(u -> !u.isBlank())
|
||||
.ifPresent(u -> {
|
||||
mailConfig.setUsername(u);
|
||||
config.services().ses().smtpPass()
|
||||
.filter(p -> !p.isBlank())
|
||||
.ifPresent(mailConfig::setPassword);
|
||||
});
|
||||
String starttls = config.services().ses().smtpStarttls();
|
||||
if ("REQUIRED".equalsIgnoreCase(starttls)) {
|
||||
mailConfig.setStarttls(StartTLSOptions.REQUIRED);
|
||||
} else if ("OPTIONAL".equalsIgnoreCase(starttls)) {
|
||||
mailConfig.setStarttls(StartTLSOptions.OPTIONAL);
|
||||
} else {
|
||||
if (!"DISABLED".equalsIgnoreCase(starttls)) {
|
||||
LOG.warnv("Unrecognized smtp-starttls value \"{0}\", defaulting to DISABLED", starttls);
|
||||
}
|
||||
mailConfig.setStarttls(StartTLSOptions.DISABLED);
|
||||
}
|
||||
return mailConfig;
|
||||
}
|
||||
|
||||
/** Package-private constructor for tests (synchronous executor, mock client). */
|
||||
SmtpRelay(MailClient mailClient, boolean enabled) {
|
||||
this.mailClient = mailClient;
|
||||
@@ -123,155 +166,399 @@ public class SmtpRelay {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* A structured (non-raw) message to relay. Built with {@link #builder(String)}; every field
|
||||
* other than the sender is optional.
|
||||
*/
|
||||
public record RelayMessage(String from, String returnPath,
|
||||
List<String> to, List<String> cc, List<String> bcc,
|
||||
List<String> replyTo,
|
||||
String subject, String bodyText, String bodyHtml,
|
||||
List<MessageHeader> headers,
|
||||
String messageId) {
|
||||
|
||||
public static Builder builder(String from) {
|
||||
return new Builder(from);
|
||||
}
|
||||
|
||||
public static final class Builder {
|
||||
private final String from;
|
||||
private String returnPath;
|
||||
private List<String> to;
|
||||
private List<String> cc;
|
||||
private List<String> bcc;
|
||||
private List<String> replyTo;
|
||||
private String subject;
|
||||
private String bodyText;
|
||||
private String bodyHtml;
|
||||
private List<MessageHeader> headers;
|
||||
private String messageId;
|
||||
|
||||
private Builder(String from) {
|
||||
this.from = from;
|
||||
}
|
||||
|
||||
public Builder returnPath(String returnPath) { this.returnPath = returnPath; return this; }
|
||||
public Builder to(List<String> to) { this.to = to; return this; }
|
||||
public Builder cc(List<String> cc) { this.cc = cc; return this; }
|
||||
public Builder bcc(List<String> bcc) { this.bcc = bcc; return this; }
|
||||
public Builder replyTo(List<String> replyTo) { this.replyTo = replyTo; return this; }
|
||||
public Builder subject(String subject) { this.subject = subject; return this; }
|
||||
public Builder bodyText(String bodyText) { this.bodyText = bodyText; return this; }
|
||||
public Builder bodyHtml(String bodyHtml) { this.bodyHtml = bodyHtml; return this; }
|
||||
public Builder headers(List<MessageHeader> headers) { this.headers = headers; return this; }
|
||||
public Builder messageId(String messageId) { this.messageId = messageId; return this; }
|
||||
|
||||
public RelayMessage build() {
|
||||
return new RelayMessage(from, returnPath, to, cc, bcc, replyTo,
|
||||
subject, bodyText, bodyHtml, headers, messageId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A raw RFC 5322 message to relay verbatim. {@code destinations} is the envelope recipient
|
||||
* list; when empty the MIME To / Cc / Bcc headers are used instead.
|
||||
*/
|
||||
public record RawRelayMessage(String from, String returnPath, List<String> destinations,
|
||||
String rawMessage, String messageId) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Relays a structured email asynchronously.
|
||||
*/
|
||||
public void relay(String from, List<String> toAddresses, List<String> ccAddresses,
|
||||
List<String> bccAddresses, List<String> replyToAddresses,
|
||||
String subject, String bodyText, String bodyHtml,
|
||||
List<MessageHeader> additionalHeaders) {
|
||||
public void relay(RelayMessage message) {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
relayExecutor.execute(() -> doRelay(from, toAddresses, ccAddresses,
|
||||
bccAddresses, replyToAddresses, subject, bodyText, bodyHtml, additionalHeaders));
|
||||
relayExecutor.execute(() -> doRelay(message));
|
||||
} catch (java.util.concurrent.RejectedExecutionException e) {
|
||||
LOG.warnv("SMTP relay skipped (executor shutting down) for from={0}", from);
|
||||
LOG.warnv("SMTP relay skipped (executor shutting down) for from={0}", message.from());
|
||||
}
|
||||
}
|
||||
|
||||
private void doRelay(String from, List<String> toAddresses, List<String> ccAddresses,
|
||||
List<String> bccAddresses, List<String> replyToAddresses,
|
||||
String subject, String bodyText, String bodyHtml,
|
||||
List<MessageHeader> additionalHeaders) {
|
||||
private void doRelay(RelayMessage message) {
|
||||
try {
|
||||
MailMessage mail = new MailMessage();
|
||||
mail.setFrom(from);
|
||||
if (toAddresses != null) {
|
||||
mail.setTo(toAddresses);
|
||||
mail.setFrom(message.from());
|
||||
applyBounceAddress(mail, message.returnPath(), message.from());
|
||||
if (message.to() != null) {
|
||||
mail.setTo(message.to());
|
||||
}
|
||||
if (ccAddresses != null) {
|
||||
mail.setCc(ccAddresses);
|
||||
if (message.cc() != null) {
|
||||
mail.setCc(message.cc());
|
||||
}
|
||||
if (bccAddresses != null) {
|
||||
mail.setBcc(bccAddresses);
|
||||
if (message.bcc() != null) {
|
||||
mail.setBcc(message.bcc());
|
||||
}
|
||||
if (replyToAddresses != null && !replyToAddresses.isEmpty()) {
|
||||
mail.addHeader("Reply-To", String.join(", ", replyToAddresses));
|
||||
if (message.replyTo() != null && !message.replyTo().isEmpty()) {
|
||||
mail.addHeader("Reply-To", String.join(", ", message.replyTo()));
|
||||
}
|
||||
if (additionalHeaders != null) {
|
||||
for (MessageHeader header : additionalHeaders) {
|
||||
if (header.isSafe()) {
|
||||
mail.addHeader(header.name(), header.value());
|
||||
} else {
|
||||
if (message.headers() != null) {
|
||||
for (MessageHeader header : message.headers()) {
|
||||
if (!header.isSafe()) {
|
||||
LOG.warnv("SMTP relay: skipping a header with a blank name or CR/LF in its "
|
||||
+ "name/value (possible header injection) for from={0}", from);
|
||||
+ "name/value (possible header injection) for from={0}", message.from());
|
||||
continue;
|
||||
}
|
||||
if (FieldName.MESSAGE_ID.equalsIgnoreCase(header.name())) {
|
||||
// AWS overrides a caller-supplied Message-ID, and rejects it outright as a
|
||||
// custom header on Simple / Templated content.
|
||||
continue;
|
||||
}
|
||||
mail.addHeader(header.name(), header.value());
|
||||
}
|
||||
}
|
||||
mail.setSubject(subject != null ? subject : "");
|
||||
if (bodyText != null) {
|
||||
mail.setText(bodyText);
|
||||
applyMessageId(mail, message.messageId());
|
||||
mail.setSubject(message.subject() != null ? message.subject() : "");
|
||||
if (message.bodyText() != null) {
|
||||
mail.setText(message.bodyText());
|
||||
}
|
||||
if (bodyHtml != null) {
|
||||
mail.setHtml(bodyHtml);
|
||||
if (message.bodyHtml() != null) {
|
||||
mail.setHtml(message.bodyHtml());
|
||||
}
|
||||
|
||||
mailClient.sendMail(mail).toCompletionStage().toCompletableFuture().get(RELAY_TIMEOUT_SECONDS, java.util.concurrent.TimeUnit.SECONDS);
|
||||
LOG.debugv("SMTP relay: sent from={0}, to={1}, subject={2}", from, toAddresses, subject);
|
||||
send(mail);
|
||||
LOG.debugv("SMTP relay: sent from={0}, to={1}, subject={2}",
|
||||
message.from(), message.to(), message.subject());
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
LOG.warnv(e, "SMTP relay interrupted for from={0}, to={1}", from, toAddresses);
|
||||
LOG.warnv(e, "SMTP relay interrupted for from={0}, to={1}", message.from(), message.to());
|
||||
} catch (java.util.concurrent.TimeoutException e) {
|
||||
LOG.warnv("SMTP relay timed out after {0}s for from={1}, to={2}", RELAY_TIMEOUT_SECONDS, from, toAddresses);
|
||||
LOG.warnv("SMTP relay timed out after {0}s for from={1}, to={2}",
|
||||
RELAY_TIMEOUT_SECONDS, message.from(), message.to());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "SMTP relay failed for from={0}, to={1}", from, toAddresses);
|
||||
LOG.warnv(e, "SMTP relay failed for from={0}, to={1}", message.from(), message.to());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Relays a raw MIME message. Parsed with Mime4j, then sent via MailClient.
|
||||
*/
|
||||
public void relayRaw(String from, List<String> destinations, String rawMessage) {
|
||||
public void relayRaw(RawRelayMessage message) {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
relayExecutor.execute(() -> doRelayRaw(from, destinations, rawMessage));
|
||||
relayExecutor.execute(() -> doRelayRaw(message));
|
||||
} catch (java.util.concurrent.RejectedExecutionException e) {
|
||||
LOG.warnv("SMTP raw relay skipped (executor shutting down) for from={0}", from);
|
||||
LOG.warnv("SMTP raw relay skipped (executor shutting down) for from={0}", message.from());
|
||||
}
|
||||
}
|
||||
|
||||
private void doRelayRaw(String from, List<String> destinations, String rawMessage) {
|
||||
private void doRelayRaw(RawRelayMessage relayMessage) {
|
||||
try {
|
||||
byte[] mimeBytes = tryBase64Decode(rawMessage);
|
||||
byte[] mimeBytes = tryBase64Decode(relayMessage.rawMessage());
|
||||
var builder = new DefaultMessageBuilder();
|
||||
var message = builder.parseMessage(new ByteArrayInputStream(mimeBytes));
|
||||
|
||||
MailMessage mail = new MailMessage();
|
||||
|
||||
// From
|
||||
// From. The display name is kept, so "Alice <alice@example.com>" is delivered as the
|
||||
// caller wrote it rather than as a bare address.
|
||||
if (message.getFrom() != null && !message.getFrom().isEmpty()) {
|
||||
mail.setFrom(message.getFrom().get(0).getAddress());
|
||||
mail.setFrom(formatMailbox(message.getFrom().get(0)));
|
||||
} else {
|
||||
mail.setFrom(from);
|
||||
mail.setFrom(relayMessage.from());
|
||||
}
|
||||
applyBounceAddress(mail, relayMessage.returnPath(), mail.getFrom());
|
||||
|
||||
// SES SendRawEmail: when Destinations is provided, it is the
|
||||
// authoritative envelope recipient list — MIME To/Cc headers are
|
||||
// display-only and must not add extra SMTP RCPT TO entries.
|
||||
List<String> destinations = relayMessage.destinations();
|
||||
if (destinations != null && !destinations.isEmpty()) {
|
||||
mail.setTo(destinations);
|
||||
} else {
|
||||
MailboxList toList = message.getTo() != null ? message.getTo().flatten() : null;
|
||||
if (toList != null && !toList.isEmpty()) {
|
||||
mail.setTo(toMailboxAddresses(toList));
|
||||
mail.setTo(formatMailboxes(toList));
|
||||
}
|
||||
MailboxList ccList = message.getCc() != null ? message.getCc().flatten() : null;
|
||||
if (ccList != null && !ccList.isEmpty()) {
|
||||
mail.setCc(toMailboxAddresses(ccList));
|
||||
mail.setCc(formatMailboxes(ccList));
|
||||
}
|
||||
MailboxList bccList = message.getBcc() != null ? message.getBcc().flatten() : null;
|
||||
if (bccList != null && !bccList.isEmpty()) {
|
||||
mail.setBcc(toMailboxAddresses(bccList));
|
||||
mail.setBcc(formatMailboxes(bccList));
|
||||
}
|
||||
}
|
||||
|
||||
// Subject
|
||||
mail.setSubject(message.getSubject() != null ? message.getSubject() : "");
|
||||
|
||||
// Body
|
||||
extractBodyFromEntity(message, mail);
|
||||
applyMimeParts(message, mail);
|
||||
copyRawHeaders(message, mail);
|
||||
applyMessageId(mail, relayMessage.messageId());
|
||||
|
||||
mailClient.sendMail(mail).toCompletionStage().toCompletableFuture().get(RELAY_TIMEOUT_SECONDS, java.util.concurrent.TimeUnit.SECONDS);
|
||||
LOG.debugv("SMTP relay: sent raw from={0}, destinations={1}", from, destinations);
|
||||
send(mail);
|
||||
LOG.debugv("SMTP relay: sent raw from={0}, destinations={1}",
|
||||
relayMessage.from(), relayMessage.destinations());
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
LOG.warnv(e, "SMTP raw relay interrupted for from={0}", from);
|
||||
LOG.warnv(e, "SMTP raw relay interrupted for from={0}", relayMessage.from());
|
||||
} catch (java.util.concurrent.TimeoutException e) {
|
||||
LOG.warnv("SMTP raw relay timed out after {0}s for from={1}", RELAY_TIMEOUT_SECONDS, from);
|
||||
LOG.warnv("SMTP raw relay timed out after {0}s for from={1}",
|
||||
RELAY_TIMEOUT_SECONDS, relayMessage.from());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "SMTP raw relay failed for from={0}", from);
|
||||
LOG.warnv(e, "SMTP raw relay failed for from={0}", relayMessage.from());
|
||||
}
|
||||
}
|
||||
|
||||
private static void extractBodyFromEntity(Entity entity, MailMessage mail) {
|
||||
private void send(MailMessage mail) throws Exception {
|
||||
mailClient.sendMail(mail).toCompletionStage().toCompletableFuture()
|
||||
.get(RELAY_TIMEOUT_SECONDS, java.util.concurrent.TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private static void applyBounceAddress(MailMessage mail, String returnPath, String fallback) {
|
||||
String bounce = firstNonBlank(returnPath, fallback);
|
||||
if (bounce != null) {
|
||||
mail.setBounceAddress(extractAngleAddress(bounce));
|
||||
}
|
||||
}
|
||||
|
||||
private static void applyMessageId(MailMessage mail, String messageId) {
|
||||
String header = formatMessageId(messageId);
|
||||
if (header != null) {
|
||||
mail.addHeader(FieldName.MESSAGE_ID, header);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats the Message-ID that AWS stamps on the delivered message. AWS documents that it
|
||||
* overrides any caller-supplied Message-ID with its own value, and that the id it assigns is
|
||||
* the {@code MessageId} returned to the caller; the local part here is therefore that id. The
|
||||
* {@code @email.amazonses.com} domain is not documented and follows observed SES output.
|
||||
* Returns null when there is no id to stamp.
|
||||
*/
|
||||
static String formatMessageId(String messageId) {
|
||||
if (messageId == null || messageId.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return "<" + messageId + "@" + MESSAGE_ID_DOMAIN + ">";
|
||||
}
|
||||
|
||||
// ──────────────────────────── Raw MIME walking ────────────────────────────
|
||||
|
||||
/** Text bodies and attachments collected from one raw MIME tree. */
|
||||
private static final class MimeParts {
|
||||
private String text;
|
||||
private String html;
|
||||
private final List<MailAttachment> attachments = new ArrayList<>();
|
||||
private final List<MailAttachment> inline = new ArrayList<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps the parsed MIME tree onto the outgoing message: the first text/plain and text/html
|
||||
* parts become the body, every other leaf becomes an attachment. Parts carrying a
|
||||
* {@code Content-ID} are relayed as inline attachments so {@code cid:} references in the HTML
|
||||
* body still resolve.
|
||||
*/
|
||||
private static void applyMimeParts(Message message, MailMessage mail) {
|
||||
MimeParts parts = new MimeParts();
|
||||
collectParts(message, parts);
|
||||
if (parts.text != null) {
|
||||
mail.setText(parts.text);
|
||||
}
|
||||
if (parts.html != null) {
|
||||
mail.setHtml(parts.html);
|
||||
}
|
||||
List<MailAttachment> attachments = new ArrayList<>(parts.attachments);
|
||||
if (parts.html != null && !parts.inline.isEmpty()) {
|
||||
mail.setInlineAttachment(parts.inline);
|
||||
} else {
|
||||
// The Vert.x encoder only emits inline attachments alongside an HTML body, so without
|
||||
// one they would be dropped silently. Relay them as regular attachments instead.
|
||||
attachments.addAll(parts.inline);
|
||||
}
|
||||
if (!attachments.isEmpty()) {
|
||||
mail.setAttachment(attachments);
|
||||
}
|
||||
}
|
||||
|
||||
private static void collectParts(Entity entity, MimeParts parts) {
|
||||
Body body = entity.getBody();
|
||||
if (body instanceof TextBody textBody) {
|
||||
// Keep the first text/plain and text/html parts encountered so that a
|
||||
// text-typed attachment later in a multipart/mixed message cannot
|
||||
// clobber the body already picked up from multipart/alternative.
|
||||
if ("text/html".equalsIgnoreCase(entity.getMimeType()) && mail.getHtml() == null) {
|
||||
mail.setHtml(readTextBody(textBody));
|
||||
} else if ("text/plain".equalsIgnoreCase(entity.getMimeType()) && mail.getText() == null) {
|
||||
mail.setText(readTextBody(textBody));
|
||||
}
|
||||
} else if (body instanceof Multipart multipart) {
|
||||
if (body instanceof Multipart multipart) {
|
||||
for (Entity part : multipart.getBodyParts()) {
|
||||
extractBodyFromEntity(part, mail);
|
||||
collectParts(part, parts);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (body instanceof TextBody textBody && !isAttachmentPart(entity)) {
|
||||
// Keep the first text/plain and text/html parts encountered so that a second one later
|
||||
// in a multipart/mixed message cannot clobber the body already picked up from
|
||||
// multipart/alternative.
|
||||
String mimeType = entity.getMimeType();
|
||||
if ("text/html".equalsIgnoreCase(mimeType)) {
|
||||
if (parts.html == null) {
|
||||
parts.html = readTextBody(textBody);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if ("text/plain".equalsIgnoreCase(mimeType)) {
|
||||
if (parts.text == null) {
|
||||
parts.text = readTextBody(textBody);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
MailAttachment attachment = toAttachment(entity, body);
|
||||
if (attachment == null) {
|
||||
return;
|
||||
}
|
||||
if (attachment.getContentId() != null) {
|
||||
parts.inline.add(attachment);
|
||||
} else {
|
||||
parts.attachments.add(attachment);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isAttachmentPart(Entity entity) {
|
||||
return "attachment".equalsIgnoreCase(entity.getDispositionType())
|
||||
|| entity.getFilename() != null
|
||||
|| headerValue(entity, FieldName.CONTENT_ID) != null;
|
||||
}
|
||||
|
||||
private static MailAttachment toAttachment(Entity entity, Body body) {
|
||||
byte[] data = readBodyBytes(body);
|
||||
if (data == null) {
|
||||
return null;
|
||||
}
|
||||
MailAttachment attachment = MailAttachment.create()
|
||||
.setData(Buffer.buffer(data))
|
||||
.setContentType(attachmentContentType(entity))
|
||||
.setName(entity.getFilename());
|
||||
String disposition = entity.getDispositionType();
|
||||
if (disposition != null && !disposition.isBlank()) {
|
||||
attachment.setDisposition(disposition);
|
||||
}
|
||||
String description = headerValue(entity, FieldName.CONTENT_DESCRIPTION);
|
||||
if (description != null) {
|
||||
attachment.setDescription(description);
|
||||
}
|
||||
String contentId = headerValue(entity, FieldName.CONTENT_ID);
|
||||
if (contentId != null) {
|
||||
attachment.setContentId(contentId);
|
||||
}
|
||||
return attachment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decoded bytes of a leaf part. An embedded message/rfc822 part is re-serialized whole so a
|
||||
* forwarded message survives the relay.
|
||||
*/
|
||||
private static byte[] readBodyBytes(Body body) {
|
||||
try {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
if (body instanceof SingleBody singleBody) {
|
||||
singleBody.writeTo(out);
|
||||
} else if (body instanceof Message embedded) {
|
||||
new DefaultMessageWriter().writeMessage(embedded, out);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
return out.toByteArray();
|
||||
} catch (IOException e) {
|
||||
LOG.warnv(e, "SMTP raw relay: could not read a MIME part, dropping it");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String attachmentContentType(Entity entity) {
|
||||
String mimeType = entity.getMimeType();
|
||||
if (mimeType == null || mimeType.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
String charset = entity.getCharset();
|
||||
if (charset != null && !charset.isBlank()
|
||||
&& mimeType.toLowerCase(Locale.ROOT).startsWith("text/")) {
|
||||
return mimeType + "; charset=" + charset;
|
||||
}
|
||||
return mimeType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the caller's top-level headers onto the relayed message. The MIME structural,
|
||||
* address and subject headers are excluded (see {@link #SUPPRESSED_RELAY_HEADERS}), as are the
|
||||
* {@code X-SES-*} control headers: AWS consumes those rather than forwarding them.
|
||||
*/
|
||||
private static void copyRawHeaders(Message message, MailMessage mail) {
|
||||
Header header = message.getHeader();
|
||||
if (header == null) {
|
||||
return;
|
||||
}
|
||||
for (Field field : header.getFields()) {
|
||||
String name = field.getName();
|
||||
if (name == null || name.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
String lower = name.toLowerCase(Locale.ROOT);
|
||||
if (SUPPRESSED_RELAY_HEADERS.contains(lower) || lower.startsWith(X_SES_PREFIX)) {
|
||||
continue;
|
||||
}
|
||||
String value = field.getBody();
|
||||
mail.addHeader(name, value == null ? "" : value.trim());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -281,25 +568,35 @@ public class SmtpRelay {
|
||||
if (textBody.getMimeCharset() != null) {
|
||||
try {
|
||||
charset = Charset.forName(textBody.getMimeCharset());
|
||||
} catch (Exception ignored) {}
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("SMTP raw relay: unknown charset \"{0}\", reading part as UTF-8",
|
||||
textBody.getMimeCharset());
|
||||
}
|
||||
}
|
||||
try (var is = textBody.getInputStream()) {
|
||||
return new String(is.readAllBytes(), charset);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "SMTP raw relay: could not read a text part, relaying it as empty");
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── Raw header parsing ────────────────────────────
|
||||
|
||||
/**
|
||||
* Structured headers extracted from a raw RFC 5322 MIME message: the From
|
||||
* address, subject, and separate To / Cc / Bcc address lists. Empty fields
|
||||
* Structured headers extracted from a raw RFC 5322 MIME message: the From address, subject,
|
||||
* separate To / Cc / Bcc address lists, the {@code Return-Path} envelope sender, and the
|
||||
* {@code X-SES-CONFIGURATION-SET} / {@code X-SES-MESSAGE-TAGS} control headers. Empty fields
|
||||
* when the corresponding header is missing.
|
||||
*/
|
||||
public record RawMessageHeaders(String from, String subject,
|
||||
List<String> to, List<String> cc, List<String> bcc) {
|
||||
List<String> to, List<String> cc, List<String> bcc,
|
||||
String returnPath, String configurationSet,
|
||||
List<MessageTag> messageTags) {
|
||||
public static RawMessageHeaders empty() {
|
||||
return new RawMessageHeaders("", "", List.of(), List.of(), List.of());
|
||||
return new RawMessageHeaders("", "", List.of(), List.of(), List.of(),
|
||||
"", "", List.of());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -325,12 +622,42 @@ public class SmtpRelay {
|
||||
? toMailboxAddresses(message.getCc().flatten()) : List.of();
|
||||
List<String> bcc = message.getBcc() != null
|
||||
? toMailboxAddresses(message.getBcc().flatten()) : List.of();
|
||||
return new RawMessageHeaders(from.isEmpty() ? "" : from.get(0), subject, to, cc, bcc);
|
||||
String returnPath = extractAngleAddress(headerValue(message, HEADER_RETURN_PATH));
|
||||
String configurationSet = headerValue(message, HEADER_CONFIGURATION_SET);
|
||||
List<MessageTag> messageTags = parseMessageTagsHeader(
|
||||
headerValue(message, HEADER_MESSAGE_TAGS));
|
||||
return new RawMessageHeaders(from.isEmpty() ? "" : from.get(0), subject, to, cc, bcc,
|
||||
returnPath == null ? "" : returnPath,
|
||||
configurationSet == null ? "" : configurationSet,
|
||||
messageTags);
|
||||
} catch (Exception e) {
|
||||
return RawMessageHeaders.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an {@code X-SES-MESSAGE-TAGS} header body: a comma-separated list of
|
||||
* {@code name=value} pairs. Entries without a name are skipped.
|
||||
*/
|
||||
static List<MessageTag> parseMessageTagsHeader(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return List.of();
|
||||
}
|
||||
List<MessageTag> tags = new ArrayList<>();
|
||||
for (String pair : value.split(",")) {
|
||||
int separator = pair.indexOf('=');
|
||||
if (separator < 0) {
|
||||
continue;
|
||||
}
|
||||
String name = pair.substring(0, separator).trim();
|
||||
if (name.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
tags.add(new MessageTag(name, pair.substring(separator + 1).trim()));
|
||||
}
|
||||
return List.copyOf(tags);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the flat list of recipients (To + Cc + Bcc) parsed from a raw RFC 5322
|
||||
* MIME message. Convenience wrapper around {@link #parseRawHeaders}.
|
||||
@@ -344,6 +671,57 @@ public class SmtpRelay {
|
||||
return all;
|
||||
}
|
||||
|
||||
private static String headerValue(Entity entity, String name) {
|
||||
Header header = entity.getHeader();
|
||||
if (header == null) {
|
||||
return null;
|
||||
}
|
||||
Field field = header.getField(name);
|
||||
if (field == null || field.getBody() == null) {
|
||||
return null;
|
||||
}
|
||||
String value = field.getBody().trim();
|
||||
return value.isEmpty() ? null : value;
|
||||
}
|
||||
|
||||
/** Unwraps the {@code <addr@example.com>} form used by Return-Path and friends. */
|
||||
static String extractAngleAddress(String value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
String trimmed = value.trim();
|
||||
if (trimmed.startsWith("<") && trimmed.endsWith(">") && trimmed.length() > 2) {
|
||||
return trimmed.substring(1, trimmed.length() - 1).trim();
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
private static String firstNonBlank(String... values) {
|
||||
for (String value : values) {
|
||||
if (value != null && !value.isBlank()) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a mailbox for a relayed header, keeping any display name. Distinct from
|
||||
* {@link #toMailboxAddresses}, which yields the bare addresses that the envelope, the
|
||||
* suppression checks and the published events work with.
|
||||
*/
|
||||
private static String formatMailbox(Mailbox mailbox) {
|
||||
return AddressFormatter.DEFAULT.encode(mailbox);
|
||||
}
|
||||
|
||||
private static List<String> formatMailboxes(MailboxList list) {
|
||||
List<String> addresses = new ArrayList<>();
|
||||
for (Mailbox mailbox : list) {
|
||||
addresses.add(formatMailbox(mailbox));
|
||||
}
|
||||
return addresses;
|
||||
}
|
||||
|
||||
private static List<String> toMailboxAddresses(MailboxList list) {
|
||||
List<String> addresses = new ArrayList<>();
|
||||
for (Mailbox mailbox : list) {
|
||||
@@ -352,11 +730,42 @@ public class SmtpRelay {
|
||||
return addresses;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes the {@code RawMessage.Data} blob, which SDK callers send base64-encoded but which
|
||||
* Floci also accepts as plain RFC 5322 text.
|
||||
*
|
||||
* <p>The alphabet is checked before decoding rather than relying on the decoder to reject
|
||||
* plain text: {@link Base64#getMimeDecoder()} skips characters outside the base64 alphabet, so
|
||||
* a plain-text message decodes into garbage whenever the remaining alphabet characters happen
|
||||
* to form a valid length. A real RFC 5322 message always carries a header separator, which is
|
||||
* not in the alphabet, so the check separates the two cases reliably.
|
||||
*/
|
||||
static byte[] tryBase64Decode(String data) {
|
||||
try {
|
||||
return Base64.getMimeDecoder().decode(data);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return data.getBytes(StandardCharsets.UTF_8);
|
||||
if (looksBase64Encoded(data)) {
|
||||
try {
|
||||
return Base64.getMimeDecoder().decode(data);
|
||||
} catch (IllegalArgumentException e) {
|
||||
LOG.debugv("SES raw message looked base64-encoded but did not decode, "
|
||||
+ "treating it as plain text");
|
||||
}
|
||||
}
|
||||
return data.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static boolean looksBase64Encoded(String data) {
|
||||
boolean sawPayload = false;
|
||||
for (int i = 0; i < data.length(); i++) {
|
||||
char c = data.charAt(i);
|
||||
if (c == '\r' || c == '\n' || c == ' ' || c == '\t' || c == '=') {
|
||||
continue;
|
||||
}
|
||||
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
|
||||
|| c == '+' || c == '/') {
|
||||
sawPayload = true;
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return sawPayload;
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,9 @@ public class SentEmail {
|
||||
@JsonProperty("Source")
|
||||
private String source;
|
||||
|
||||
@JsonProperty("ReturnPath")
|
||||
private String returnPath;
|
||||
|
||||
@JsonProperty("Destination")
|
||||
private List<String> toAddresses;
|
||||
|
||||
@@ -92,6 +95,9 @@ public class SentEmail {
|
||||
public String getSource() { return source; }
|
||||
public void setSource(String source) { this.source = source; }
|
||||
|
||||
public String getReturnPath() { return returnPath; }
|
||||
public void setReturnPath(String returnPath) { this.returnPath = returnPath; }
|
||||
|
||||
public List<String> getToAddresses() { return toAddresses; }
|
||||
public void setToAddresses(List<String> toAddresses) { this.toAddresses = toAddresses; }
|
||||
|
||||
|
||||
+4
-3
@@ -39,6 +39,7 @@ 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;
|
||||
@@ -941,7 +942,7 @@ class CognitoLambdaTriggersTest {
|
||||
|
||||
verify(ses).sendEmail(
|
||||
anyString(), eq(List.of("spike@example.com")),
|
||||
eq(List.of()), eq(List.of()), eq(List.of()),
|
||||
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(), anyString());
|
||||
@@ -998,7 +999,7 @@ class CognitoLambdaTriggersTest {
|
||||
|
||||
verify(ses).sendEmail(
|
||||
anyString(), eq(List.of("spike@example.com")),
|
||||
any(), any(), any(),
|
||||
any(), any(), any(), isNull(),
|
||||
eq("Your verification code"),
|
||||
eq("Your verification code is 246962."),
|
||||
any(), any(), any(), any(), any(), anyString());
|
||||
@@ -1022,7 +1023,7 @@ class CognitoLambdaTriggersTest {
|
||||
verify(lambdaService, never()).invoke(anyString(), anyString(), any(byte[].class), any());
|
||||
verify(ses).sendEmail(
|
||||
anyString(), eq(List.of("spike@example.com")),
|
||||
any(), any(), any(),
|
||||
any(), any(), any(), isNull(),
|
||||
eq("Your verification code"),
|
||||
eq("Your verification code is 246962."),
|
||||
any(), any(), any(), any(), any(), anyString());
|
||||
|
||||
+5
-4
@@ -46,7 +46,7 @@ class CognitoMessageDispatcherTest {
|
||||
verify(ses).sendEmail(
|
||||
anyString(),
|
||||
eq(List.of("alice@example.com")),
|
||||
eq(List.of()), eq(List.of()), eq(List.of()),
|
||||
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()),
|
||||
@@ -102,7 +102,7 @@ class CognitoMessageDispatcherTest {
|
||||
|
||||
verify(ses).sendEmail(
|
||||
anyString(), eq(List.of("alice@example.com")),
|
||||
eq(List.of()), eq(List.of()), eq(List.of()),
|
||||
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(), eq("us-east-1"));
|
||||
@@ -118,7 +118,7 @@ class CognitoMessageDispatcherTest {
|
||||
|
||||
verify(ses).sendEmail(
|
||||
anyString(), eq(List.of("alice@example.com")),
|
||||
eq(List.of()), eq(List.of()), eq(List.of()),
|
||||
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(), eq("us-east-1"));
|
||||
@@ -133,7 +133,8 @@ class CognitoMessageDispatcherTest {
|
||||
"444555", List.of());
|
||||
|
||||
verify(ses).sendEmail(anyString(), eq(List.of("alice@example.com")),
|
||||
any(), any(), any(), anyString(), anyString(), isNull(), isNull(), any(), any(), isNull(), anyString());
|
||||
any(), any(), any(), isNull(), anyString(), anyString(), isNull(), isNull(), any(), any(),
|
||||
isNull(), anyString());
|
||||
verifyNoInteractions(sns);
|
||||
}
|
||||
|
||||
|
||||
+73
@@ -1677,4 +1677,77 @@ class SesEventPublishingV2IntegrationTest {
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(30)
|
||||
void v1SendRawEmail_xSesControlHeaders_selectConfigurationSetAndSupplyTags() throws Exception {
|
||||
drainQueue();
|
||||
// Neither ConfigurationSetName nor Tags is sent as a request field: AWS reads both from the
|
||||
// message itself on a raw send, so the events only reach the topic if the headers are honoured.
|
||||
String raw = "From: " + SENDER + "\r\n"
|
||||
+ "To: success@simulator.amazonses.com\r\n"
|
||||
+ "Subject: header-driven\r\n"
|
||||
+ "X-SES-CONFIGURATION-SET: " + CS + "\r\n"
|
||||
+ "X-SES-MESSAGE-TAGS: campaign=headercampaign, env=headerenv\r\n"
|
||||
+ "\r\nbody";
|
||||
String rawB64 = java.util.Base64.getEncoder().encodeToString(
|
||||
raw.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", SES_AUTH)
|
||||
.body("Action=SendRawEmail"
|
||||
+ "&Source=" + java.net.URLEncoder.encode(SENDER, java.nio.charset.StandardCharsets.UTF_8)
|
||||
+ "&RawMessage.Data=" + java.net.URLEncoder.encode(rawB64, java.nio.charset.StandardCharsets.UTF_8)
|
||||
+ "&Version=2010-12-01")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
List<JsonNode> events = receiveSesEvents(2);
|
||||
JsonNode send = events.stream()
|
||||
.filter(e -> "Send".equals(e.path("eventType").asText()))
|
||||
.findFirst().orElseThrow();
|
||||
JsonNode tags = send.path("mail").path("tags");
|
||||
assertEquals(CS, tags.path("ses:configuration-set").get(0).asText());
|
||||
assertEquals("headercampaign", tags.path("campaign").get(0).asText());
|
||||
assertEquals("headerenv", tags.path("env").get(0).asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(31)
|
||||
void v1SendRawEmail_requestTagsReplaceTheHeaderTagsEntirely() throws Exception {
|
||||
drainQueue();
|
||||
String raw = "From: " + SENDER + "\r\n"
|
||||
+ "To: success@simulator.amazonses.com\r\n"
|
||||
+ "Subject: header-vs-request\r\n"
|
||||
+ "X-SES-MESSAGE-TAGS: campaign=fromheader, only=inheader\r\n"
|
||||
+ "\r\nbody";
|
||||
String rawB64 = java.util.Base64.getEncoder().encodeToString(
|
||||
raw.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", SES_AUTH)
|
||||
.body("Action=SendRawEmail"
|
||||
+ "&Source=" + java.net.URLEncoder.encode(SENDER, java.nio.charset.StandardCharsets.UTF_8)
|
||||
+ "&RawMessage.Data=" + java.net.URLEncoder.encode(rawB64, java.nio.charset.StandardCharsets.UTF_8)
|
||||
+ "&Tags.member.1.Name=campaign&Tags.member.1.Value=fromrequest"
|
||||
+ "&ConfigurationSetName=" + CS
|
||||
+ "&Version=2010-12-01")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
List<JsonNode> events = receiveSesEvents(2);
|
||||
JsonNode send = events.stream()
|
||||
.filter(e -> "Send".equals(e.path("eventType").asText()))
|
||||
.findFirst().orElseThrow();
|
||||
JsonNode tags = send.path("mail").path("tags");
|
||||
assertEquals("fromrequest", tags.path("campaign").get(0).asText());
|
||||
// AWS uses only the API parameter's tags when both are given and does not join the two
|
||||
// sets, so a header-only tag is dropped rather than merged in.
|
||||
assertTrue(tags.path("only").isMissingNode() || tags.path("only").isEmpty(),
|
||||
"header tags must be discarded entirely when the request supplies tags: " + tags);
|
||||
}
|
||||
}
|
||||
@@ -446,6 +446,65 @@ class SesIntegrationTest {
|
||||
.body("messages[0].ReplyToAddresses", hasItem("reply@example.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(21)
|
||||
void sendEmailV1_returnPathStoredInInspection() {
|
||||
given().delete("/_aws/ses").then().statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request")
|
||||
.formParam("Action", "SendEmail")
|
||||
.formParam("Source", "sender@example.com")
|
||||
.formParam("Destination.ToAddresses.member.1", "recipient@example.com")
|
||||
.formParam("ReturnPath", "bounces@example.com")
|
||||
.formParam("Message.Subject.Data", "V1 ReturnPath")
|
||||
.formParam("Message.Body.Text.Data", "body")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/_aws/ses")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("messages[0].ReturnPath", equalTo("bounces@example.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(21)
|
||||
void sendRawEmailV1_returnPathHeaderStoredInInspection() {
|
||||
given().delete("/_aws/ses").then().statusCode(200);
|
||||
|
||||
String raw = "From: sender@example.com\r\n"
|
||||
+ "To: recipient@example.com\r\n"
|
||||
+ "Return-Path: <mime-bounces@example.com>\r\n"
|
||||
+ "Subject: raw-return-path\r\n\r\nbody";
|
||||
String rawB64 = java.util.Base64.getEncoder().encodeToString(
|
||||
raw.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request")
|
||||
.formParam("Action", "SendRawEmail")
|
||||
.formParam("Source", "sender@example.com")
|
||||
.formParam("Destinations.member.1", "recipient@example.com")
|
||||
.formParam("RawMessage.Data", rawB64)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/_aws/ses")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("messages[0].ReturnPath", equalTo("mime-bounces@example.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(22)
|
||||
void deleteDomainIdentity() {
|
||||
|
||||
+19
-21
@@ -62,17 +62,21 @@ class SesServiceListManagementTest {
|
||||
}
|
||||
|
||||
private void send(List<String> to, String topicName) {
|
||||
service.sendEmail(FROM, to, null, null, null, "Subject", "body", null,
|
||||
service.sendEmail(FROM, to, null, null, null, null, "Subject", "body", null,
|
||||
null, List.of(), List.of(), new ListManagementOptions(LIST, topicName), REGION);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private List<String> capturedRelayTo() {
|
||||
ArgumentCaptor<List<String>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(smtpRelay).relay(any(), captor.capture(), any(), any(), any(), any(), any(), any(), any());
|
||||
private SmtpRelay.RelayMessage capturedRelay() {
|
||||
ArgumentCaptor<SmtpRelay.RelayMessage> captor =
|
||||
ArgumentCaptor.forClass(SmtpRelay.RelayMessage.class);
|
||||
verify(smtpRelay).relay(captor.capture());
|
||||
return captor.getValue();
|
||||
}
|
||||
|
||||
private List<String> capturedRelayTo() {
|
||||
return capturedRelay().to();
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsubscribeAll_isSuppressed_evenWithNoTopic() {
|
||||
send(List.of("unsub@example.com", "sportsin@example.com"), null);
|
||||
@@ -96,7 +100,7 @@ class SesServiceListManagementTest {
|
||||
void topicDefaultOptOut_suppressesContactWithNoExplicitPreference() {
|
||||
// Promos defaults OPT_OUT and noprefs has no explicit Promos preference -> suppressed.
|
||||
send(List.of("noprefs@example.com"), "Promos");
|
||||
verify(smtpRelay, never()).relay(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
verify(smtpRelay, never()).relay(any(SmtpRelay.RelayMessage.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -116,7 +120,7 @@ class SesServiceListManagementTest {
|
||||
@Test
|
||||
void nonExistentContactList_failsTheSend() {
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
service.sendEmail(FROM, List.of("sportsin@example.com"), null, null, null,
|
||||
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), REGION));
|
||||
assertEquals(404, ex.getHttpStatus());
|
||||
@@ -126,7 +130,7 @@ 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,
|
||||
service.sendEmail(FROM, List.of("sportsin@example.com"), null, null, null, null,
|
||||
"Subject", "body", null, null, List.of(), List.of(),
|
||||
new ListManagementOptions(LIST, "GhostTopic"), REGION));
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
@@ -136,7 +140,7 @@ 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,
|
||||
service.sendEmail(FROM, List.of("unsub@example.com"), null, null, null, null,
|
||||
"Subject", "body", null, null, List.of(), List.of(), null, REGION);
|
||||
assertEquals(List.of("unsub@example.com"), capturedRelayTo());
|
||||
}
|
||||
@@ -144,7 +148,7 @@ class SesServiceListManagementTest {
|
||||
@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,
|
||||
service.sendEmail(FROM, List.of("newbie@example.com"), null, null, null, null,
|
||||
"Subject", "text", "<p>Unsub: {{amazonSESUnsubscribeUrl}}</p>",
|
||||
null, List.of(), List.of(), new ListManagementOptions(LIST, "Sports"), REGION);
|
||||
String html = capturedRelayBodyHtml();
|
||||
@@ -157,7 +161,7 @@ class SesServiceListManagementTest {
|
||||
@Test
|
||||
void multiRecipient_doesNotReplacePlaceholder() {
|
||||
service.sendEmail(FROM, List.of("newbie@example.com", "sportsin@example.com"), null, null, null,
|
||||
"Subject", "text", "<p>Unsub: {{amazonSESUnsubscribeUrl}}</p>",
|
||||
null, "Subject", "text", "<p>Unsub: {{amazonSESUnsubscribeUrl}}</p>",
|
||||
null, List.of(), List.of(), new ListManagementOptions(LIST, "Sports"), REGION);
|
||||
assertTrue(capturedRelayBodyHtml().contains("{{amazonSESUnsubscribeUrl}}"),
|
||||
"multi-recipient send must not inject the unsubscribe link");
|
||||
@@ -199,23 +203,17 @@ class SesServiceListManagementTest {
|
||||
return contactStore.get("contact::" + REGION + "::" + LIST + "::" + email).orElseThrow();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private String capturedRelayBodyHtml() {
|
||||
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
|
||||
verify(smtpRelay).relay(any(), any(), any(), any(), any(), any(), any(), captor.capture(), any());
|
||||
return captor.getValue();
|
||||
return capturedRelay().bodyHtml();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private List<MessageHeader> capturedRelayHeaders() {
|
||||
ArgumentCaptor<List<MessageHeader>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(smtpRelay).relay(any(), any(), any(), any(), any(), any(), any(), any(), captor.capture());
|
||||
return captor.getValue();
|
||||
return capturedRelay().headers();
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleRecipient_addsListUnsubscribeHeadersToRelay() {
|
||||
service.sendEmail(FROM, List.of("newbie@example.com"), null, null, null,
|
||||
service.sendEmail(FROM, List.of("newbie@example.com"), null, null, null, null,
|
||||
"Subject", "text", "<p>x</p>", null, List.of(), List.of(),
|
||||
new ListManagementOptions(LIST, "Sports"), REGION);
|
||||
List<MessageHeader> headers = capturedRelayHeaders();
|
||||
@@ -227,7 +225,7 @@ class SesServiceListManagementTest {
|
||||
|
||||
@Test
|
||||
void callerSuppliedUnsubscribeHeader_isOverriddenNotDuplicated() {
|
||||
service.sendEmail(FROM, List.of("newbie@example.com"), null, null, null,
|
||||
service.sendEmail(FROM, List.of("newbie@example.com"), null, null, null, null,
|
||||
"Subject", "text", "<p>x</p>", null, List.of(),
|
||||
List.of(new MessageHeader("List-Unsubscribe", "<https://caller.example/u>")),
|
||||
new ListManagementOptions(LIST, "Sports"), REGION);
|
||||
|
||||
@@ -9,6 +9,8 @@ import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
@@ -29,68 +31,140 @@ class SesServiceSmtpTest {
|
||||
service = builder.build();
|
||||
}
|
||||
|
||||
private SentEmail storedEmail(String messageId) {
|
||||
return service.getEmails().stream()
|
||||
.filter(e -> messageId.equals(e.getMessageId()))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
}
|
||||
|
||||
private SmtpRelay.RelayMessage capturedRelay() {
|
||||
ArgumentCaptor<SmtpRelay.RelayMessage> captor =
|
||||
ArgumentCaptor.forClass(SmtpRelay.RelayMessage.class);
|
||||
verify(smtpRelay).relay(captor.capture());
|
||||
return captor.getValue();
|
||||
}
|
||||
|
||||
private SmtpRelay.RawRelayMessage capturedRawRelay() {
|
||||
ArgumentCaptor<SmtpRelay.RawRelayMessage> captor =
|
||||
ArgumentCaptor.forClass(SmtpRelay.RawRelayMessage.class);
|
||||
verify(smtpRelay).relayRaw(captor.capture());
|
||||
return captor.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendEmail_callsRelayWithAllFields() {
|
||||
service.sendEmail("from@example.com",
|
||||
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", "<p>html</p>", null, List.of(), List.of(), null, "us-east-1");
|
||||
|
||||
verify(smtpRelay).relay(
|
||||
"from@example.com",
|
||||
List.of("to@example.com"),
|
||||
List.of("cc@example.com"),
|
||||
List.of("bcc@example.com"),
|
||||
List.of("reply@example.com"),
|
||||
"Subject", "text body", "<p>html</p>", List.of());
|
||||
SmtpRelay.RelayMessage relayed = capturedRelay();
|
||||
assertEquals("from@example.com", relayed.from());
|
||||
assertEquals(List.of("to@example.com"), relayed.to());
|
||||
assertEquals(List.of("cc@example.com"), relayed.cc());
|
||||
assertEquals(List.of("bcc@example.com"), relayed.bcc());
|
||||
assertEquals(List.of("reply@example.com"), relayed.replyTo());
|
||||
assertEquals("Subject", relayed.subject());
|
||||
assertEquals("text body", relayed.bodyText());
|
||||
assertEquals("<p>html</p>", relayed.bodyHtml());
|
||||
assertEquals(List.of(), relayed.headers());
|
||||
assertEquals(messageId, relayed.messageId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendEmail_storesAndRelays() {
|
||||
String messageId = service.sendEmail("from@example.com",
|
||||
List.of("to@example.com"), null, null, null,
|
||||
List.of("to@example.com"), null, null, null, null,
|
||||
"Subject", "text", null, null, List.of(), List.of(), null, "us-east-1");
|
||||
|
||||
assertNotNull(messageId);
|
||||
assertFalse(emailStore.scan(k -> true).isEmpty());
|
||||
verify(smtpRelay).relay(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
verify(smtpRelay).relay(any(SmtpRelay.RelayMessage.class));
|
||||
}
|
||||
|
||||
@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, "us-east-1");
|
||||
|
||||
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, "us-east-1");
|
||||
|
||||
assertEquals("bounces@example.com", capturedRelay().returnPath());
|
||||
assertEquals("bounces@example.com", storedEmail(messageId).getReturnPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendRawEmail_callsRelayRaw() {
|
||||
service.sendRawEmail("from@example.com",
|
||||
List.of("to@example.com"), "raw MIME", null, List.of(), null, "us-east-1");
|
||||
String messageId = service.sendRawEmail("from@example.com",
|
||||
List.of("to@example.com"), "raw MIME", null, null, List.of(), null, "us-east-1");
|
||||
|
||||
verify(smtpRelay).relayRaw(
|
||||
"from@example.com",
|
||||
List.of("to@example.com"),
|
||||
"raw MIME");
|
||||
SmtpRelay.RawRelayMessage relayed = capturedRawRelay();
|
||||
assertEquals("from@example.com", relayed.from());
|
||||
assertEquals(List.of("to@example.com"), relayed.destinations());
|
||||
assertEquals("raw MIME", relayed.rawMessage());
|
||||
assertEquals(messageId, relayed.messageId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendRawEmail_returnPathHeader_winsOverRequestField() {
|
||||
String raw = "From: from@example.com\r\n"
|
||||
+ "To: to@example.com\r\n"
|
||||
+ "Return-Path: <mime-bounces@example.com>\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, "us-east-1");
|
||||
|
||||
assertEquals("mime-bounces@example.com", capturedRawRelay().returnPath());
|
||||
assertEquals("mime-bounces@example.com", storedEmail(messageId).getReturnPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
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, "us-east-1");
|
||||
|
||||
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, List.of(), null, "us-east-1");
|
||||
List.of("to@example.com"), "raw", null, null, List.of(), null, "us-east-1");
|
||||
|
||||
assertNotNull(messageId);
|
||||
assertFalse(emailStore.scan(k -> true).isEmpty());
|
||||
verify(smtpRelay).relayRaw(any(), any(), any());
|
||||
verify(smtpRelay).relayRaw(any(SmtpRelay.RawRelayMessage.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendEmail_relayReceivesCorrectFieldsWithNulls() {
|
||||
service.sendEmail("from@example.com",
|
||||
List.of("to@example.com"),
|
||||
null, null, null,
|
||||
null, null, null, null,
|
||||
"Subject", null, "<p>html only</p>", null, List.of(), List.of(), null, "us-east-1");
|
||||
|
||||
verify(smtpRelay).relay(
|
||||
"from@example.com",
|
||||
List.of("to@example.com"),
|
||||
null, null, null,
|
||||
"Subject", null, "<p>html only</p>", List.of());
|
||||
SmtpRelay.RelayMessage relayed = capturedRelay();
|
||||
assertEquals(List.of("to@example.com"), relayed.to());
|
||||
assertNull(relayed.cc());
|
||||
assertNull(relayed.bcc());
|
||||
assertNull(relayed.replyTo());
|
||||
assertNull(relayed.bodyText());
|
||||
assertEquals("<p>html only</p>", relayed.bodyHtml());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -101,13 +175,13 @@ class SesServiceSmtpTest {
|
||||
String messageId = service.sendEmail("from@example.com",
|
||||
List.of("to@example.com"),
|
||||
List.of("cc@example.com"),
|
||||
null, null,
|
||||
null, null, null,
|
||||
"Subject", "text body", null, null, List.of(), List.of(), null, "us-east-1");
|
||||
|
||||
assertNotNull(messageId);
|
||||
assertFalse(emailStore.scan(k -> true).isEmpty(),
|
||||
"stored SentEmail should still record the original recipient list");
|
||||
verify(smtpRelay, never()).relay(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
verify(smtpRelay, never()).relay(any(SmtpRelay.RelayMessage.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -118,16 +192,12 @@ class SesServiceSmtpTest {
|
||||
service.sendEmail("from@example.com",
|
||||
List.of("to@example.com", "suppressed@example.com"),
|
||||
List.of("cc-keep@example.com"),
|
||||
null, null,
|
||||
null, null, null,
|
||||
"Subject", "text body", null, null, List.of(), List.of(), null, "us-east-1");
|
||||
|
||||
verify(smtpRelay).relay(
|
||||
"from@example.com",
|
||||
List.of("to@example.com"),
|
||||
List.of("cc-keep@example.com"),
|
||||
null,
|
||||
null,
|
||||
"Subject", "text body", null, List.of());
|
||||
SmtpRelay.RelayMessage relayed = capturedRelay();
|
||||
assertEquals(List.of("to@example.com"), relayed.to());
|
||||
assertEquals(List.of("cc-keep@example.com"), relayed.cc());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -135,11 +205,11 @@ class SesServiceSmtpTest {
|
||||
service.putSuppressedDestination("us-east-1", "to@example.com", "BOUNCE");
|
||||
|
||||
String messageId = service.sendRawEmail("from@example.com",
|
||||
List.of("to@example.com"), "raw MIME", null, List.of(), null, "us-east-1");
|
||||
List.of("to@example.com"), "raw MIME", null, null, List.of(), null, "us-east-1");
|
||||
|
||||
assertNotNull(messageId);
|
||||
assertFalse(emailStore.scan(k -> true).isEmpty());
|
||||
verify(smtpRelay, never()).relayRaw(any(), any(), any());
|
||||
verify(smtpRelay, never()).relayRaw(any(SmtpRelay.RawRelayMessage.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -148,12 +218,9 @@ class SesServiceSmtpTest {
|
||||
|
||||
service.sendRawEmail("from@example.com",
|
||||
List.of("to@example.com", "suppressed@example.com"),
|
||||
"raw MIME", null, List.of(), null, "us-east-1");
|
||||
"raw MIME", null, null, List.of(), null, "us-east-1");
|
||||
|
||||
verify(smtpRelay).relayRaw(
|
||||
"from@example.com",
|
||||
List.of("to@example.com"),
|
||||
"raw MIME");
|
||||
assertEquals(List.of("to@example.com"), capturedRawRelay().destinations());
|
||||
}
|
||||
|
||||
// ─────────── Per-CS SuppressionOptions override at send time ───────────
|
||||
@@ -169,14 +236,10 @@ class SesServiceSmtpTest {
|
||||
service.putConfigurationSetSuppressionOptions("cs-no-suppression", List.of(), "us-east-1");
|
||||
|
||||
service.sendEmail("from@example.com",
|
||||
List.of("to@example.com"), null, null, null,
|
||||
List.of("to@example.com"), null, null, null, null,
|
||||
"Subject", "text body", null, "cs-no-suppression", List.of(), List.of(), null, "us-east-1");
|
||||
|
||||
verify(smtpRelay).relay(
|
||||
"from@example.com",
|
||||
List.of("to@example.com"),
|
||||
null, null, null,
|
||||
"Subject", "text body", null, List.of());
|
||||
assertEquals(List.of("to@example.com"), capturedRelay().to());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -189,14 +252,10 @@ class SesServiceSmtpTest {
|
||||
service.putConfigurationSetSuppressionOptions("cs-bounce-only", List.of("BOUNCE"), "us-east-1");
|
||||
|
||||
service.sendEmail("from@example.com",
|
||||
List.of("complainer@example.com"), null, null, null,
|
||||
List.of("complainer@example.com"), null, null, null, null,
|
||||
"Subject", "text body", null, "cs-bounce-only", List.of(), List.of(), null, "us-east-1");
|
||||
|
||||
verify(smtpRelay).relay(
|
||||
"from@example.com",
|
||||
List.of("complainer@example.com"),
|
||||
null, null, null,
|
||||
"Subject", "text body", null, List.of());
|
||||
assertEquals(List.of("complainer@example.com"), capturedRelay().to());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -208,10 +267,10 @@ class SesServiceSmtpTest {
|
||||
service.createConfigurationSet(new ConfigurationSet("cs-default"), "us-east-1");
|
||||
|
||||
service.sendEmail("from@example.com",
|
||||
List.of("to@example.com"), null, null, null,
|
||||
List.of("to@example.com"), null, null, null, null,
|
||||
"Subject", "text body", null, "cs-default", List.of(), List.of(), null, "us-east-1");
|
||||
|
||||
verify(smtpRelay, never()).relay(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
verify(smtpRelay, never()).relay(any(SmtpRelay.RelayMessage.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -221,11 +280,9 @@ class SesServiceSmtpTest {
|
||||
service.putConfigurationSetSuppressionOptions("cs-no-suppression-raw", List.of(), "us-east-1");
|
||||
|
||||
service.sendRawEmail("from@example.com",
|
||||
List.of("to@example.com"), "raw MIME", "cs-no-suppression-raw", List.of(), null, "us-east-1");
|
||||
List.of("to@example.com"), "raw MIME", null, "cs-no-suppression-raw", List.of(), null,
|
||||
"us-east-1");
|
||||
|
||||
verify(smtpRelay).relayRaw(
|
||||
"from@example.com",
|
||||
List.of("to@example.com"),
|
||||
"raw MIME");
|
||||
assertEquals(List.of("to@example.com"), capturedRawRelay().destinations());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.ext.mail.MailClient;
|
||||
import io.vertx.ext.mail.MailConfig;
|
||||
import io.vertx.ext.mail.StartTLSOptions;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.net.InetAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Drives the relay through a real Vert.x {@link MailClient} against an in-process SMTP server, so
|
||||
* the assertions cover what a mocked client cannot: the SMTP envelope actually negotiated, and the
|
||||
* bytes the encoder puts on the wire.
|
||||
*/
|
||||
class SmtpRelayServerTest {
|
||||
|
||||
private static StubSmtpServer server;
|
||||
private static Vertx vertx;
|
||||
|
||||
private final List<MailClient> clients = new ArrayList<>();
|
||||
|
||||
@BeforeAll
|
||||
static void startServer() throws IOException {
|
||||
server = new StubSmtpServer();
|
||||
vertx = Vertx.vertx();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void closeClients() {
|
||||
// Vert.x pools SMTP connections, so an unclosed client keeps its socket open and the next
|
||||
// test would assert against a stale session.
|
||||
clients.forEach(MailClient::close);
|
||||
clients.clear();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopServer() throws IOException {
|
||||
server.close();
|
||||
vertx.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the relay the way CDI would, then swaps in the synchronous-executor constructor so the
|
||||
* assertions run after delivery rather than racing it. The authentication and STARTTLS-OPTIONAL
|
||||
* branches of {@link SmtpRelay#buildMailConfig} are exercised on the way through.
|
||||
*/
|
||||
private SmtpRelay relayAgainstServer() {
|
||||
MailConfig mailConfig = SmtpRelay.buildMailConfig(
|
||||
config("relay-user", "relay-pass", "OPTIONAL"),
|
||||
server.host(), server.port());
|
||||
MailClient client = MailClient.create(vertx, mailConfig);
|
||||
clients.add(client);
|
||||
return new SmtpRelay(client, true);
|
||||
}
|
||||
|
||||
private static EmulatorConfig config(String user, String pass, String starttls) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, org.mockito.Mockito.RETURNS_DEEP_STUBS);
|
||||
when(config.services().ses().smtpUser()).thenReturn(Optional.ofNullable(user));
|
||||
when(config.services().ses().smtpPass()).thenReturn(Optional.ofNullable(pass));
|
||||
when(config.services().ses().smtpStarttls()).thenReturn(starttls);
|
||||
return config;
|
||||
}
|
||||
|
||||
@Test
|
||||
void rawRelay_deliversEnvelopeHeadersAndAttachmentOverSmtp() throws Exception {
|
||||
server.reset();
|
||||
String attachmentBody = Base64.getEncoder().encodeToString(
|
||||
"PDF-PAYLOAD".getBytes(StandardCharsets.UTF_8));
|
||||
String rawMime = "From: Alice Sender <sender@example.com>\r\n"
|
||||
+ "To: Bob <to@example.com>\r\n"
|
||||
+ "Subject: Real SMTP\r\n"
|
||||
+ "Return-Path: <bounces@example.com>\r\n"
|
||||
+ "X-Custom: keep-me\r\n"
|
||||
+ "X-SES-CONFIGURATION-SET: my-config-set\r\n"
|
||||
+ "MIME-Version: 1.0\r\n"
|
||||
+ "Content-Type: multipart/mixed; boundary=\"outer\"\r\n"
|
||||
+ "\r\n"
|
||||
+ "--outer\r\n"
|
||||
+ "Content-Type: text/plain; charset=UTF-8\r\n"
|
||||
+ "\r\n"
|
||||
+ "the real body\r\n"
|
||||
+ "--outer\r\n"
|
||||
+ "Content-Type: application/pdf\r\n"
|
||||
+ "Content-Disposition: attachment; filename=\"report.pdf\"\r\n"
|
||||
+ "Content-Transfer-Encoding: base64\r\n"
|
||||
+ "\r\n"
|
||||
+ attachmentBody + "\r\n"
|
||||
+ "--outer--";
|
||||
|
||||
relayAgainstServer().relayRaw(new SmtpRelay.RawRelayMessage("sender@example.com",
|
||||
"bounces@example.com", List.of("dest@example.com"), rawMime, "msg-42"));
|
||||
|
||||
assertTrue(server.awaitDelivery(), "the stub server should have accepted a message");
|
||||
assertEquals("bounces@example.com", server.mailFrom(),
|
||||
"the Return-Path must become the SMTP envelope sender");
|
||||
assertEquals(List.of("dest@example.com"), server.recipients());
|
||||
|
||||
String data = server.data();
|
||||
assertTrue(data.contains("Message-ID: <msg-42@email.amazonses.com>"), data);
|
||||
assertTrue(data.contains("From: Alice Sender <sender@example.com>"),
|
||||
"the display name must survive the relay: " + data);
|
||||
assertTrue(data.contains("X-Custom: keep-me"), data);
|
||||
assertTrue(data.contains("the real body"), data);
|
||||
assertTrue(data.contains("report.pdf"), data);
|
||||
assertTrue(data.contains(attachmentBody), "the attachment payload must survive the relay");
|
||||
// AWS consumes the X-SES-* control headers rather than forwarding them.
|
||||
assertFalse(data.contains("X-SES-CONFIGURATION-SET"), data);
|
||||
// The caller's Content-Type described the original tree, which the encoder has rebuilt.
|
||||
assertFalse(data.contains("boundary=\"outer\""), data);
|
||||
}
|
||||
|
||||
@Test
|
||||
void structuredRelay_usesReturnPathAsEnvelopeSenderAndStampsMessageId() throws Exception {
|
||||
server.reset();
|
||||
|
||||
relayAgainstServer().relay(SmtpRelay.RelayMessage.builder("sender@example.com")
|
||||
.returnPath("bounces@example.com")
|
||||
.to(List.of("to@example.com"))
|
||||
.cc(List.of("cc@example.com"))
|
||||
.subject("Structured")
|
||||
.bodyText("plain body")
|
||||
.headers(List.of(new MessageHeader("X-Custom", "kept")))
|
||||
.messageId("msg-7")
|
||||
.build());
|
||||
|
||||
assertTrue(server.awaitDelivery(), "the stub server should have accepted a message");
|
||||
assertEquals("bounces@example.com", server.mailFrom());
|
||||
assertEquals(List.of("to@example.com", "cc@example.com"), server.recipients());
|
||||
|
||||
String data = server.data();
|
||||
assertTrue(data.contains("Message-ID: <msg-7@email.amazonses.com>"), data);
|
||||
assertTrue(data.contains("X-Custom: kept"), data);
|
||||
assertTrue(data.contains("plain body"), data);
|
||||
}
|
||||
|
||||
@Test
|
||||
void relay_authenticatesWithTheConfiguredCredentials() throws Exception {
|
||||
server.reset();
|
||||
|
||||
relayAgainstServer().relay(SmtpRelay.RelayMessage.builder("sender@example.com")
|
||||
.to(List.of("to@example.com"))
|
||||
.subject("Auth")
|
||||
.bodyText("body")
|
||||
.build());
|
||||
|
||||
assertTrue(server.awaitDelivery());
|
||||
String auth = server.authCommand();
|
||||
assertNotNull(auth, "the relay should authenticate when smtp-user is configured");
|
||||
String credentials = new String(Base64.getDecoder().decode(auth.substring("AUTH PLAIN ".length())),
|
||||
StandardCharsets.UTF_8);
|
||||
assertEquals("\0relay-user\0relay-pass", credentials);
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildMailConfig_mapsStarttlsModesAndFallsBackToDisabled() {
|
||||
assertEquals(StartTLSOptions.REQUIRED,
|
||||
SmtpRelay.buildMailConfig(config(null, null, "required"), "h", 25).getStarttls());
|
||||
assertEquals(StartTLSOptions.OPTIONAL,
|
||||
SmtpRelay.buildMailConfig(config(null, null, "OPTIONAL"), "h", 25).getStarttls());
|
||||
assertEquals(StartTLSOptions.DISABLED,
|
||||
SmtpRelay.buildMailConfig(config(null, null, "DISABLED"), "h", 25).getStarttls());
|
||||
assertEquals(StartTLSOptions.DISABLED,
|
||||
SmtpRelay.buildMailConfig(config(null, null, "nonsense"), "h", 25).getStarttls());
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildMailConfig_withoutAUsername_leavesCredentialsUnset() {
|
||||
MailConfig mailConfig = SmtpRelay.buildMailConfig(config(" ", "pass", "DISABLED"), "h", 25);
|
||||
assertNull(mailConfig.getUsername());
|
||||
assertNull(mailConfig.getPassword());
|
||||
}
|
||||
|
||||
/**
|
||||
* A minimal SMTP server: enough of the protocol for a real {@link MailClient} to complete a
|
||||
* session, capturing the envelope and the DATA payload.
|
||||
*/
|
||||
private static final class StubSmtpServer implements AutoCloseable {
|
||||
|
||||
private final ServerSocket serverSocket;
|
||||
private final Thread acceptThread;
|
||||
private volatile java.util.concurrent.CountDownLatch delivered =
|
||||
new java.util.concurrent.CountDownLatch(1);
|
||||
private volatile String mailFrom;
|
||||
private volatile String authCommand;
|
||||
private volatile String data;
|
||||
private volatile List<String> recipients = new ArrayList<>();
|
||||
|
||||
StubSmtpServer() throws IOException {
|
||||
serverSocket = new ServerSocket(0, 16, InetAddress.getLoopbackAddress());
|
||||
acceptThread = new Thread(this::acceptLoop, "stub-smtp");
|
||||
acceptThread.setDaemon(true);
|
||||
acceptThread.start();
|
||||
}
|
||||
|
||||
String host() {
|
||||
return serverSocket.getInetAddress().getHostAddress();
|
||||
}
|
||||
|
||||
int port() {
|
||||
return serverSocket.getLocalPort();
|
||||
}
|
||||
|
||||
void reset() {
|
||||
delivered = new java.util.concurrent.CountDownLatch(1);
|
||||
mailFrom = null;
|
||||
authCommand = null;
|
||||
data = null;
|
||||
recipients = new ArrayList<>();
|
||||
}
|
||||
|
||||
boolean awaitDelivery() throws InterruptedException {
|
||||
return delivered.await(20, java.util.concurrent.TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
String mailFrom() {
|
||||
return mailFrom;
|
||||
}
|
||||
|
||||
List<String> recipients() {
|
||||
return recipients;
|
||||
}
|
||||
|
||||
String data() {
|
||||
return data;
|
||||
}
|
||||
|
||||
String authCommand() {
|
||||
return authCommand;
|
||||
}
|
||||
|
||||
private void acceptLoop() {
|
||||
while (!serverSocket.isClosed()) {
|
||||
try {
|
||||
Socket socket = serverSocket.accept();
|
||||
// Vert.x keeps the connection pooled after a send, so the session is handled off
|
||||
// the accept loop: otherwise the first idle connection blocks every later test.
|
||||
Thread worker = new Thread(() -> {
|
||||
try (socket) {
|
||||
converse(socket);
|
||||
} catch (IOException e) {
|
||||
// The client closed the pooled connection; nothing left to serve.
|
||||
}
|
||||
}, "stub-smtp-session");
|
||||
worker.setDaemon(true);
|
||||
worker.start();
|
||||
} catch (IOException e) {
|
||||
if (!serverSocket.isClosed()) {
|
||||
throw new IllegalStateException("stub SMTP server failed", e);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void converse(Socket socket) throws IOException {
|
||||
BufferedReader in = new BufferedReader(
|
||||
new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
|
||||
BufferedWriter out = new BufferedWriter(
|
||||
new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
|
||||
reply(out, "220 floci-stub ESMTP");
|
||||
|
||||
String line;
|
||||
while ((line = in.readLine()) != null) {
|
||||
String command = line.toUpperCase(Locale.ROOT);
|
||||
if (command.startsWith("EHLO")) {
|
||||
reply(out, "250-floci-stub");
|
||||
reply(out, "250 AUTH PLAIN");
|
||||
} else if (command.startsWith("HELO")) {
|
||||
reply(out, "250 floci-stub");
|
||||
} else if (command.startsWith("AUTH")) {
|
||||
authCommand = line;
|
||||
reply(out, "235 2.7.0 Authentication successful");
|
||||
} else if (command.startsWith("MAIL FROM")) {
|
||||
mailFrom = address(line);
|
||||
reply(out, "250 OK");
|
||||
} else if (command.startsWith("RCPT TO")) {
|
||||
recipients.add(address(line));
|
||||
reply(out, "250 OK");
|
||||
} else if (command.startsWith("DATA")) {
|
||||
reply(out, "354 End data with <CR><LF>.<CR><LF>");
|
||||
data = readData(in);
|
||||
reply(out, "250 OK: queued");
|
||||
delivered.countDown();
|
||||
} else if (command.startsWith("QUIT")) {
|
||||
reply(out, "221 Bye");
|
||||
return;
|
||||
} else if (command.startsWith("RSET") || command.startsWith("NOOP")) {
|
||||
reply(out, "250 OK");
|
||||
} else {
|
||||
reply(out, "500 Unrecognized command");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String readData(BufferedReader in) throws IOException {
|
||||
StringBuilder body = new StringBuilder();
|
||||
String line;
|
||||
while ((line = in.readLine()) != null && !".".equals(line)) {
|
||||
// Undo the dot-stuffing the client applies to lines starting with a period.
|
||||
body.append(line.startsWith("..") ? line.substring(1) : line).append("\r\n");
|
||||
}
|
||||
return body.toString();
|
||||
}
|
||||
|
||||
private static String address(String line) {
|
||||
int start = line.indexOf('<');
|
||||
int end = line.indexOf('>', start + 1);
|
||||
return start >= 0 && end > start ? line.substring(start + 1, end) : "";
|
||||
}
|
||||
|
||||
private static void reply(BufferedWriter out, String response) throws IOException {
|
||||
out.write(response);
|
||||
out.write("\r\n");
|
||||
out.flush();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
serverSocket.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import io.github.hectorvent.floci.services.ses.model.MessageHeader;
|
||||
import io.github.hectorvent.floci.services.ses.model.MessageTag;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.ext.mail.MailAttachment;
|
||||
import io.vertx.ext.mail.MailClient;
|
||||
import io.vertx.ext.mail.MailMessage;
|
||||
import io.vertx.ext.mail.MailResult;
|
||||
@@ -22,6 +24,19 @@ class SmtpRelayTest {
|
||||
|
||||
@Mock MailClient mailClient;
|
||||
|
||||
private static SmtpRelay.RelayMessage simple(String text) {
|
||||
return SmtpRelay.RelayMessage.builder("from@example.com")
|
||||
.to(List.of("to@example.com"))
|
||||
.subject("Subject")
|
||||
.bodyText(text)
|
||||
.headers(List.of())
|
||||
.build();
|
||||
}
|
||||
|
||||
private static SmtpRelay.RawRelayMessage raw(String from, List<String> destinations, String rawMessage) {
|
||||
return new SmtpRelay.RawRelayMessage(from, null, destinations, rawMessage, null);
|
||||
}
|
||||
|
||||
private SmtpRelay enabledRelay() {
|
||||
when(mailClient.sendMail(any(MailMessage.class)))
|
||||
.thenReturn(Future.succeededFuture(new MailResult()));
|
||||
@@ -33,8 +48,7 @@ class SmtpRelayTest {
|
||||
SmtpRelay relay = new SmtpRelay(mailClient, false);
|
||||
assertFalse(relay.isEnabled());
|
||||
|
||||
relay.relay("from@example.com", List.of("to@example.com"),
|
||||
null, null, null, "Subject", "text", null, List.of());
|
||||
relay.relay(simple("text"));
|
||||
|
||||
verify(mailClient, never()).sendMail(any(MailMessage.class));
|
||||
}
|
||||
@@ -43,14 +57,16 @@ class SmtpRelayTest {
|
||||
void relay_whenEnabled_sendsMail() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
relay.relay("from@example.com",
|
||||
List.of("to@example.com"),
|
||||
List.of("cc@example.com"),
|
||||
List.of("bcc@example.com"),
|
||||
List.of("reply@example.com"),
|
||||
"Test Subject",
|
||||
"plain text",
|
||||
"<p>html</p>", List.of());
|
||||
relay.relay(SmtpRelay.RelayMessage.builder("from@example.com")
|
||||
.to(List.of("to@example.com"))
|
||||
.cc(List.of("cc@example.com"))
|
||||
.bcc(List.of("bcc@example.com"))
|
||||
.replyTo(List.of("reply@example.com"))
|
||||
.subject("Test Subject")
|
||||
.bodyText("plain text")
|
||||
.bodyHtml("<p>html</p>")
|
||||
.headers(List.of())
|
||||
.build());
|
||||
|
||||
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
|
||||
verify(mailClient).sendMail(captor.capture());
|
||||
@@ -70,8 +86,7 @@ class SmtpRelayTest {
|
||||
void relay_noReplyTo_omitsHeader() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
relay.relay("from@example.com", List.of("to@example.com"),
|
||||
null, null, null, "Subject", "text", null, List.of());
|
||||
relay.relay(simple("text"));
|
||||
|
||||
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
|
||||
verify(mailClient).sendMail(captor.capture());
|
||||
@@ -82,12 +97,16 @@ class SmtpRelayTest {
|
||||
void relay_dropsHeadersWithCrlfOrBlankName_preventingInjection() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
relay.relay("from@example.com", List.of("to@example.com"),
|
||||
null, null, null, "Subject", "text", null, List.of(
|
||||
relay.relay(SmtpRelay.RelayMessage.builder("from@example.com")
|
||||
.to(List.of("to@example.com"))
|
||||
.subject("Subject")
|
||||
.bodyText("text")
|
||||
.headers(List.of(
|
||||
new MessageHeader("X-Safe", "ok"),
|
||||
new MessageHeader("X-Evil", "value\r\nBcc: attacker@evil.com"),
|
||||
new MessageHeader("Injected\r\nBcc", "x"),
|
||||
new MessageHeader("", "no-name")));
|
||||
new MessageHeader("", "no-name")))
|
||||
.build());
|
||||
|
||||
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
|
||||
verify(mailClient).sendMail(captor.capture());
|
||||
@@ -106,8 +125,7 @@ class SmtpRelayTest {
|
||||
void relay_textOnly_setsTextWithoutHtml() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
relay.relay("from@example.com", List.of("to@example.com"),
|
||||
null, null, null, "Subject", "only text", null, List.of());
|
||||
relay.relay(simple("only text"));
|
||||
|
||||
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
|
||||
verify(mailClient).sendMail(captor.capture());
|
||||
@@ -119,8 +137,11 @@ class SmtpRelayTest {
|
||||
void relay_htmlOnly_setsHtmlWithoutText() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
relay.relay("from@example.com", List.of("to@example.com"),
|
||||
null, null, null, "Subject", null, "<b>html</b>", List.of());
|
||||
relay.relay(SmtpRelay.RelayMessage.builder("from@example.com")
|
||||
.to(List.of("to@example.com"))
|
||||
.subject("Subject")
|
||||
.bodyHtml("<b>html</b>")
|
||||
.build());
|
||||
|
||||
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
|
||||
verify(mailClient).sendMail(captor.capture());
|
||||
@@ -134,8 +155,7 @@ class SmtpRelayTest {
|
||||
when(mailClient.sendMail(any(MailMessage.class)))
|
||||
.thenReturn(Future.failedFuture(new RuntimeException("SMTP refused")));
|
||||
|
||||
assertDoesNotThrow(() -> relay.relay("from@example.com",
|
||||
List.of("to@example.com"), null, null, null, "Subject", "text", null, List.of()));
|
||||
assertDoesNotThrow(() -> relay.relay(simple("text")));
|
||||
}
|
||||
|
||||
// ── Raw relay ──
|
||||
@@ -144,7 +164,7 @@ class SmtpRelayTest {
|
||||
void relayRaw_whenDisabled_doesNotSend() {
|
||||
SmtpRelay relay = new SmtpRelay(mailClient, false);
|
||||
|
||||
relay.relayRaw("from@example.com", List.of("to@example.com"), "raw");
|
||||
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), "raw"));
|
||||
|
||||
verify(mailClient, never()).sendMail(any(MailMessage.class));
|
||||
}
|
||||
@@ -159,7 +179,7 @@ class SmtpRelayTest {
|
||||
+ "Content-Type: text/plain; charset=UTF-8\r\n"
|
||||
+ "\r\n"
|
||||
+ "Raw body content";
|
||||
relay.relayRaw("envelope@example.com", List.of("dest@example.com"), rawMime);
|
||||
relay.relayRaw(raw("envelope@example.com", List.of("dest@example.com"), rawMime));
|
||||
|
||||
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
|
||||
verify(mailClient).sendMail(captor.capture());
|
||||
@@ -178,7 +198,7 @@ class SmtpRelayTest {
|
||||
String rawMime = "From: s@example.com\r\nTo: t@example.com\r\nSubject: B64\r\n\r\nDecoded body";
|
||||
String encoded = java.util.Base64.getEncoder().encodeToString(
|
||||
rawMime.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
relay.relayRaw("from@example.com", List.of("to@example.com"), encoded);
|
||||
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), encoded));
|
||||
|
||||
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
|
||||
verify(mailClient).sendMail(captor.capture());
|
||||
@@ -192,7 +212,7 @@ class SmtpRelayTest {
|
||||
|
||||
String rawMime = "From: s@example.com\r\nTo: t@example.com\r\nSubject: HTML\r\n"
|
||||
+ "Content-Type: text/html; charset=UTF-8\r\n\r\n<h1>Hello</h1>";
|
||||
relay.relayRaw("from@example.com", List.of("to@example.com"), rawMime);
|
||||
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), rawMime));
|
||||
|
||||
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
|
||||
verify(mailClient).sendMail(captor.capture());
|
||||
@@ -212,7 +232,7 @@ class SmtpRelayTest {
|
||||
+ "Content-Type: text/plain; charset=UTF-8\r\n"
|
||||
+ "\r\n"
|
||||
+ "body";
|
||||
relay.relayRaw("envelope@example.com", null, rawMime);
|
||||
relay.relayRaw(raw("envelope@example.com", null, rawMime));
|
||||
|
||||
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
|
||||
verify(mailClient).sendMail(captor.capture());
|
||||
@@ -227,7 +247,7 @@ class SmtpRelayTest {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
String rawMime = "Subject: NoAddr\r\n\r\nBody";
|
||||
relay.relayRaw("envelope@example.com", List.of("dest@example.com"), rawMime);
|
||||
relay.relayRaw(raw("envelope@example.com", List.of("dest@example.com"), rawMime));
|
||||
|
||||
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
|
||||
verify(mailClient).sendMail(captor.capture());
|
||||
@@ -257,7 +277,7 @@ class SmtpRelayTest {
|
||||
+ "<p>html</p>\r\n"
|
||||
+ "--inner--\r\n"
|
||||
+ "--outer--";
|
||||
relay.relayRaw("from@example.com", List.of("to@example.com"), rawMime);
|
||||
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), rawMime));
|
||||
|
||||
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
|
||||
verify(mailClient).sendMail(captor.capture());
|
||||
@@ -284,7 +304,7 @@ class SmtpRelayTest {
|
||||
+ "\r\n"
|
||||
+ "attachment content that must not clobber body\r\n"
|
||||
+ "--outer--";
|
||||
relay.relayRaw("from@example.com", List.of("to@example.com"), rawMime);
|
||||
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), rawMime));
|
||||
|
||||
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
|
||||
verify(mailClient).sendMail(captor.capture());
|
||||
@@ -297,8 +317,8 @@ class SmtpRelayTest {
|
||||
when(mailClient.sendMail(any(MailMessage.class)))
|
||||
.thenReturn(Future.failedFuture(new RuntimeException("SMTP timeout")));
|
||||
|
||||
assertDoesNotThrow(() -> relay.relayRaw("from@example.com",
|
||||
List.of("to@example.com"), "Subject: X\r\n\r\nBody"));
|
||||
assertDoesNotThrow(() -> relay.relayRaw(raw("from@example.com",
|
||||
List.of("to@example.com"), "Subject: X\r\n\r\nBody")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -321,6 +341,25 @@ class SmtpRelayTest {
|
||||
assertEquals(List.of("only@example.com"), SmtpRelay.parseRawRecipients(b64));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tryBase64Decode_plainTextMime_isNotTreatedAsBase64() {
|
||||
// The MIME decoder skips characters outside the base64 alphabet, so a plain-text message
|
||||
// whose remaining alphabet characters happen to form a valid length would otherwise decode
|
||||
// into garbage.
|
||||
String raw = "From: s@example.com\r\nMessage-ID: <caller@example.com>\r\nSubject: x\r\n\r\nbody";
|
||||
assertEquals(raw, new String(SmtpRelay.tryBase64Decode(raw),
|
||||
java.nio.charset.StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tryBase64Decode_base64Payload_isDecoded() {
|
||||
String raw = "From: s@example.com\r\nSubject: x\r\n\r\nbody";
|
||||
String encoded = java.util.Base64.getEncoder().encodeToString(
|
||||
raw.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
assertEquals(raw, new String(SmtpRelay.tryBase64Decode(encoded),
|
||||
java.nio.charset.StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseRawRecipients_blankOrUnparseable_returnsEmpty() {
|
||||
assertTrue(SmtpRelay.parseRawRecipients(null).isEmpty());
|
||||
@@ -358,4 +397,392 @@ class SmtpRelayTest {
|
||||
assertTrue(h.cc().isEmpty());
|
||||
assertTrue(h.bcc().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseRawHeaders_extractsReturnPathAndSesControlHeaders() {
|
||||
String raw = "From: sender@example.com\r\n"
|
||||
+ "To: to@example.com\r\n"
|
||||
+ "Return-Path: <bounces@example.com>\r\n"
|
||||
+ "X-SES-CONFIGURATION-SET: my-config-set\r\n"
|
||||
+ "X-SES-MESSAGE-TAGS: campaign=spring, tier=gold\r\n"
|
||||
+ "Subject: x\r\n\r\nbody";
|
||||
|
||||
SmtpRelay.RawMessageHeaders h = SmtpRelay.parseRawHeaders(raw);
|
||||
|
||||
assertEquals("bounces@example.com", h.returnPath());
|
||||
assertEquals("my-config-set", h.configurationSet());
|
||||
assertEquals(List.of(new MessageTag("campaign", "spring"), new MessageTag("tier", "gold")),
|
||||
h.messageTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseRawHeaders_withoutSesHeaders_returnsBlanksAndNoTags() {
|
||||
String raw = "From: sender@example.com\r\nTo: to@example.com\r\nSubject: x\r\n\r\nbody";
|
||||
|
||||
SmtpRelay.RawMessageHeaders h = SmtpRelay.parseRawHeaders(raw);
|
||||
|
||||
assertEquals("", h.returnPath());
|
||||
assertEquals("", h.configurationSet());
|
||||
assertTrue(h.messageTags().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseMessageTagsHeader_skipsEntriesWithoutAName() {
|
||||
assertEquals(List.of(new MessageTag("ok", "1")),
|
||||
SmtpRelay.parseMessageTagsHeader("ok=1, =2, novalueseparator"));
|
||||
assertTrue(SmtpRelay.parseMessageTagsHeader(null).isEmpty());
|
||||
assertTrue(SmtpRelay.parseMessageTagsHeader(" ").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatMessageId_usesTheReturnedMessageIdAsTheLocalPart() {
|
||||
assertEquals("<abc-123@email.amazonses.com>", SmtpRelay.formatMessageId("abc-123"));
|
||||
assertNull(SmtpRelay.formatMessageId(null));
|
||||
assertNull(SmtpRelay.formatMessageId(" "));
|
||||
}
|
||||
|
||||
// ── Envelope sender and Message-ID ──
|
||||
|
||||
@Test
|
||||
void relay_returnPath_becomesTheEnvelopeSender() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
relay.relay(SmtpRelay.RelayMessage.builder("from@example.com")
|
||||
.returnPath("bounces@example.com")
|
||||
.to(List.of("to@example.com"))
|
||||
.subject("Subject")
|
||||
.bodyText("text")
|
||||
.build());
|
||||
|
||||
assertEquals("bounces@example.com", captureSent().getBounceAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
void relay_noReturnPath_envelopeSenderFallsBackToFrom() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
relay.relay(simple("text"));
|
||||
|
||||
assertEquals("from@example.com", captureSent().getBounceAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
void relay_stampsMessageIdInTheAwsFormat() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
relay.relay(SmtpRelay.RelayMessage.builder("from@example.com")
|
||||
.to(List.of("to@example.com"))
|
||||
.subject("Subject")
|
||||
.bodyText("text")
|
||||
.messageId("msg-1")
|
||||
.build());
|
||||
|
||||
assertEquals("<msg-1@email.amazonses.com>",
|
||||
captureSent().getHeaders().get("Message-ID"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void relay_callerSuppliedMessageIdHeader_isOverridden() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
relay.relay(SmtpRelay.RelayMessage.builder("from@example.com")
|
||||
.to(List.of("to@example.com"))
|
||||
.subject("Subject")
|
||||
.bodyText("text")
|
||||
.headers(List.of(new MessageHeader("Message-ID", "<caller@example.com>")))
|
||||
.messageId("msg-1")
|
||||
.build());
|
||||
|
||||
// AWS overrides a caller-supplied Message-ID with the id it assigned.
|
||||
assertEquals(List.of("<msg-1@email.amazonses.com>"),
|
||||
captureSent().getHeaders().getAll("Message-ID"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void relayRaw_returnPath_becomesTheEnvelopeSender() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
relay.relayRaw(new SmtpRelay.RawRelayMessage("from@example.com", "bounces@example.com",
|
||||
List.of("to@example.com"), "From: s@example.com\r\nSubject: x\r\n\r\nbody",
|
||||
"msg-1"));
|
||||
|
||||
assertEquals("bounces@example.com", captureSent().getBounceAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
void relayRaw_stampsMessageIdWhenTheMessageHasNone() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
relay.relayRaw(new SmtpRelay.RawRelayMessage("from@example.com", null,
|
||||
List.of("to@example.com"), "From: s@example.com\r\nSubject: x\r\n\r\nbody",
|
||||
"msg-1"));
|
||||
|
||||
assertEquals("<msg-1@email.amazonses.com>",
|
||||
captureSent().getHeaders().get("Message-ID"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void relayRaw_overridesACallerSuppliedMessageId() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
String rawMime = "From: s@example.com\r\n"
|
||||
+ "Message-ID: <caller-supplied@example.com>\r\n"
|
||||
+ "Subject: x\r\n\r\nbody";
|
||||
relay.relayRaw(new SmtpRelay.RawRelayMessage("from@example.com", null,
|
||||
List.of("to@example.com"), rawMime, "msg-1"));
|
||||
|
||||
// AWS overrides a caller-supplied Message-ID with the id it assigned.
|
||||
assertEquals(List.of("<msg-1@email.amazonses.com>"),
|
||||
captureSent().getHeaders().getAll("Message-ID"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void relayRaw_dropsACallerSuppliedDate() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
String rawMime = "From: s@example.com\r\n"
|
||||
+ "Date: Mon, 08 Oct 2018 14:05:45 +0000\r\n"
|
||||
+ "Subject: x\r\n\r\nbody";
|
||||
relay.relayRaw(new SmtpRelay.RawRelayMessage("from@example.com", null,
|
||||
List.of("to@example.com"), rawMime, "msg-1"));
|
||||
|
||||
// AWS replaces the caller's Date with the time it accepted the message, so the stale value
|
||||
// must not be carried onto the relayed message; the encoder generates the send-time Date.
|
||||
MailMessage sent = captureSent();
|
||||
assertNull(sent.getHeaders().get("Date"));
|
||||
assertEquals("<msg-1@email.amazonses.com>", sent.getHeaders().get("Message-ID"));
|
||||
}
|
||||
|
||||
// ── Raw relay fidelity: headers and attachments ──
|
||||
|
||||
@Test
|
||||
void relayRaw_copiesCustomHeadersButNotStructuralOrSesOnes() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
String rawMime = "From: s@example.com\r\n"
|
||||
+ "To: t@example.com\r\n"
|
||||
+ "Subject: Headers\r\n"
|
||||
+ "Reply-To: reply@example.com\r\n"
|
||||
+ "X-Custom: keep-me\r\n"
|
||||
+ "X-SES-CONFIGURATION-SET: cs\r\n"
|
||||
+ "X-SES-MESSAGE-TAGS: a=b\r\n"
|
||||
+ "Return-Path: <bounces@example.com>\r\n"
|
||||
+ "MIME-Version: 1.0\r\n"
|
||||
+ "Content-Type: text/plain; charset=UTF-8\r\n"
|
||||
+ "\r\n"
|
||||
+ "body";
|
||||
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), rawMime));
|
||||
|
||||
MailMessage sent = captureSent();
|
||||
assertEquals("keep-me", sent.getHeaders().get("X-Custom"));
|
||||
assertEquals("reply@example.com", sent.getHeaders().get("Reply-To"));
|
||||
// AWS consumes the X-SES-* control headers rather than forwarding them, and the MIME
|
||||
// structural headers are regenerated for the re-built message.
|
||||
assertFalse(sent.getHeaders().contains("X-SES-CONFIGURATION-SET"));
|
||||
assertFalse(sent.getHeaders().contains("X-SES-MESSAGE-TAGS"));
|
||||
assertFalse(sent.getHeaders().contains("Content-Type"));
|
||||
assertFalse(sent.getHeaders().contains("MIME-Version"));
|
||||
assertFalse(sent.getHeaders().contains("Return-Path"));
|
||||
assertFalse(sent.getHeaders().contains("Date"));
|
||||
assertFalse(sent.getHeaders().contains("Subject"));
|
||||
assertFalse(sent.getHeaders().contains("From"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void relayRaw_keepsDisplayNamesOnAddresses() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
String rawMime = "From: Alice Sender <alice@example.com>\r\n"
|
||||
+ "To: Bob Recipient <bob@example.com>\r\n"
|
||||
+ "Cc: Carol <carol@example.com>\r\n"
|
||||
+ "Subject: Names\r\n\r\nbody";
|
||||
relay.relayRaw(raw("envelope@example.com", null, rawMime));
|
||||
|
||||
MailMessage sent = captureSent();
|
||||
assertEquals("Alice Sender <alice@example.com>", sent.getFrom());
|
||||
assertEquals(List.of("Bob Recipient <bob@example.com>"), sent.getTo());
|
||||
assertEquals(List.of("Carol <carol@example.com>"), sent.getCc());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseRawRecipients_stripsDisplayNames() {
|
||||
// The envelope, suppression checks and published events all work with bare addresses.
|
||||
String raw = "From: Alice <alice@example.com>\r\n"
|
||||
+ "To: Bob Recipient <bob@example.com>\r\n"
|
||||
+ "Subject: x\r\n\r\nbody";
|
||||
assertEquals(List.of("bob@example.com"), SmtpRelay.parseRawRecipients(raw));
|
||||
assertEquals("alice@example.com", SmtpRelay.parseRawHeaders(raw).from());
|
||||
}
|
||||
|
||||
@Test
|
||||
void relayRaw_preservesAttachments() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
String rawMime = "From: s@example.com\r\n"
|
||||
+ "To: t@example.com\r\n"
|
||||
+ "Subject: WithAttachment\r\n"
|
||||
+ "Content-Type: multipart/mixed; boundary=\"outer\"\r\n"
|
||||
+ "\r\n"
|
||||
+ "--outer\r\n"
|
||||
+ "Content-Type: text/plain; charset=UTF-8\r\n"
|
||||
+ "\r\n"
|
||||
+ "the body\r\n"
|
||||
+ "--outer\r\n"
|
||||
+ "Content-Type: application/pdf\r\n"
|
||||
+ "Content-Disposition: attachment; filename=\"report.pdf\"\r\n"
|
||||
+ "Content-Description: Quarterly report\r\n"
|
||||
+ "Content-Transfer-Encoding: base64\r\n"
|
||||
+ "\r\n"
|
||||
+ java.util.Base64.getEncoder().encodeToString("PDF-BYTES".getBytes(
|
||||
java.nio.charset.StandardCharsets.UTF_8)) + "\r\n"
|
||||
+ "--outer--";
|
||||
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), rawMime));
|
||||
|
||||
MailMessage sent = captureSent();
|
||||
assertEquals("the body", sent.getText().trim());
|
||||
assertNotNull(sent.getAttachment());
|
||||
assertEquals(1, sent.getAttachment().size());
|
||||
MailAttachment attachment = sent.getAttachment().get(0);
|
||||
assertEquals("report.pdf", attachment.getName());
|
||||
assertEquals("application/pdf", attachment.getContentType());
|
||||
assertEquals("attachment", attachment.getDisposition());
|
||||
assertEquals("Quarterly report", attachment.getDescription());
|
||||
assertEquals("PDF-BYTES", attachment.getData().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void relayRaw_embeddedRfc822Part_isReserializedWhole() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
String rawMime = "From: s@example.com\r\n"
|
||||
+ "To: t@example.com\r\n"
|
||||
+ "Subject: Fwd: original\r\n"
|
||||
+ "Content-Type: multipart/mixed; boundary=\"fwd\"\r\n"
|
||||
+ "\r\n"
|
||||
+ "--fwd\r\n"
|
||||
+ "Content-Type: text/plain; charset=UTF-8\r\n"
|
||||
+ "\r\n"
|
||||
+ "see the forwarded note\r\n"
|
||||
+ "--fwd\r\n"
|
||||
+ "Content-Type: message/rfc822\r\n"
|
||||
+ "Content-Disposition: attachment; filename=\"original.eml\"\r\n"
|
||||
+ "\r\n"
|
||||
+ "From: inner@example.com\r\n"
|
||||
+ "To: t@example.com\r\n"
|
||||
+ "Subject: original\r\n"
|
||||
+ "\r\n"
|
||||
+ "inner body\r\n"
|
||||
+ "--fwd--";
|
||||
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), rawMime));
|
||||
|
||||
MailMessage sent = captureSent();
|
||||
assertEquals("see the forwarded note", sent.getText().trim());
|
||||
assertNotNull(sent.getAttachment());
|
||||
assertEquals(1, sent.getAttachment().size());
|
||||
MailAttachment forwarded = sent.getAttachment().get(0);
|
||||
assertEquals("original.eml", forwarded.getName());
|
||||
assertEquals("message/rfc822", forwarded.getContentType());
|
||||
// The embedded message is written back out as a complete RFC 822 stream, headers and all,
|
||||
// which is the DefaultMessageWriter path that needs mime4j -core and -dom to agree.
|
||||
String reserialized = forwarded.getData().toString();
|
||||
assertTrue(reserialized.contains("From: inner@example.com"),
|
||||
"forwarded headers should survive, got: " + reserialized);
|
||||
assertTrue(reserialized.contains("Subject: original"),
|
||||
"forwarded headers should survive, got: " + reserialized);
|
||||
assertTrue(reserialized.contains("inner body"),
|
||||
"forwarded body should survive, got: " + reserialized);
|
||||
}
|
||||
|
||||
@Test
|
||||
void relayRaw_contentIdPart_becomesAnInlineAttachment() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
String rawMime = "From: s@example.com\r\n"
|
||||
+ "To: t@example.com\r\n"
|
||||
+ "Subject: Inline\r\n"
|
||||
+ "Content-Type: multipart/related; boundary=\"rel\"\r\n"
|
||||
+ "\r\n"
|
||||
+ "--rel\r\n"
|
||||
+ "Content-Type: text/html; charset=UTF-8\r\n"
|
||||
+ "\r\n"
|
||||
+ "<img src=\"cid:logo\">\r\n"
|
||||
+ "--rel\r\n"
|
||||
+ "Content-Type: image/png\r\n"
|
||||
+ "Content-ID: <logo>\r\n"
|
||||
+ "Content-Transfer-Encoding: base64\r\n"
|
||||
+ "\r\n"
|
||||
+ java.util.Base64.getEncoder().encodeToString("PNG".getBytes(
|
||||
java.nio.charset.StandardCharsets.UTF_8)) + "\r\n"
|
||||
+ "--rel--";
|
||||
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), rawMime));
|
||||
|
||||
MailMessage sent = captureSent();
|
||||
assertNull(sent.getAttachment());
|
||||
assertNotNull(sent.getInlineAttachment());
|
||||
assertEquals(1, sent.getInlineAttachment().size());
|
||||
MailAttachment inline = sent.getInlineAttachment().get(0);
|
||||
assertEquals("<logo>", inline.getContentId());
|
||||
assertEquals("image/png", inline.getContentType());
|
||||
assertEquals("PNG", inline.getData().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void relayRaw_inlineAttachmentWithoutHtmlBody_isRelayedAsARegularAttachment() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
String rawMime = "From: s@example.com\r\n"
|
||||
+ "To: t@example.com\r\n"
|
||||
+ "Subject: InlineNoHtml\r\n"
|
||||
+ "Content-Type: multipart/related; boundary=\"rel\"\r\n"
|
||||
+ "\r\n"
|
||||
+ "--rel\r\n"
|
||||
+ "Content-Type: text/plain; charset=UTF-8\r\n"
|
||||
+ "\r\n"
|
||||
+ "plain only\r\n"
|
||||
+ "--rel\r\n"
|
||||
+ "Content-Type: image/png\r\n"
|
||||
+ "Content-ID: <logo>\r\n"
|
||||
+ "\r\n"
|
||||
+ "PNG\r\n"
|
||||
+ "--rel--";
|
||||
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), rawMime));
|
||||
|
||||
MailMessage sent = captureSent();
|
||||
assertNull(sent.getInlineAttachment());
|
||||
assertNotNull(sent.getAttachment());
|
||||
assertEquals(1, sent.getAttachment().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void relayRaw_textAttachmentDoesNotClobberTheBody() {
|
||||
SmtpRelay relay = enabledRelay();
|
||||
|
||||
String rawMime = "From: s@example.com\r\n"
|
||||
+ "To: t@example.com\r\n"
|
||||
+ "Subject: Mixed\r\n"
|
||||
+ "Content-Type: multipart/mixed; boundary=\"outer\"\r\n"
|
||||
+ "\r\n"
|
||||
+ "--outer\r\n"
|
||||
+ "Content-Type: text/plain; charset=UTF-8\r\n"
|
||||
+ "\r\n"
|
||||
+ "real body\r\n"
|
||||
+ "--outer\r\n"
|
||||
+ "Content-Type: text/plain; charset=UTF-8\r\n"
|
||||
+ "Content-Disposition: attachment; filename=\"notes.txt\"\r\n"
|
||||
+ "\r\n"
|
||||
+ "attachment content\r\n"
|
||||
+ "--outer--";
|
||||
relay.relayRaw(raw("from@example.com", List.of("to@example.com"), rawMime));
|
||||
|
||||
MailMessage sent = captureSent();
|
||||
assertEquals("real body", sent.getText().trim());
|
||||
assertEquals(1, sent.getAttachment().size());
|
||||
assertEquals("notes.txt", sent.getAttachment().get(0).getName());
|
||||
}
|
||||
|
||||
private MailMessage captureSent() {
|
||||
ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);
|
||||
verify(mailClient).sendMail(captor.capture());
|
||||
return captor.getValue();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user