fix(ses): skip the raw relay when the message cannot be parsed or is nested too deeply (#9066)

This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-11-19 21:55:32 -04:00
1 parent 0af048a099
commit a769b77124
7 files changed
+73 -15

No files matched your search

@@ -636,7 +636,7 @@ public class SesService {
List<String> relayedDestinations = filterUnsuppressed(effectiveDestinations, suppressedReasons);
if (!rejected && !relayedDestinations.isEmpty()) {
smtpRelay.relayRaw(new SmtpRelay.RawRelayMessage(effectiveSource, effectiveReturnPath,
relayedDestinations, raw.data(), messageId));
relayedDestinations, parsed.message(), messageId));
} else {
LOG.infov("SES raw email accepted but not relayed ({0}): messageId={1}",
rejected ? "content rejected" : "all recipients suppressed", messageId);
@@ -27,12 +27,10 @@ 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.io.InputStream;
@@ -237,10 +235,19 @@ public class SmtpRelay {
/**
* 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.
* list; when empty the MIME To / Cc / Bcc headers are used instead. {@code message} is the
* parsed message, {@code null} when the parser could not read it, in which case nothing is
* relayed. mime4j parses header fields lazily and without synchronization, so the relay
* thread owns {@code message} once it is handed over: the caller must not read it afterwards.
*/
public record RawRelayMessage(String from, String returnPath, List<String> destinations,
String rawMessage, String messageId) {
Message message, String messageId) {
/** Parses {@code rawMessage} (plain or base64-encoded) for callers that hold only the text. */
public RawRelayMessage(String from, String returnPath, List<String> destinations,
String rawMessage, String messageId) {
this(from, returnPath, destinations, SesMimeParser.parse(tryBase64Decode(rawMessage)), messageId);
}
}
/**
@@ -413,9 +420,12 @@ public class SmtpRelay {
private void doRelayRaw(RawRelayMessage relayMessage) {
try {
byte[] mimeBytes = tryBase64Decode(relayMessage.rawMessage());
DefaultMessageBuilder builder = new DefaultMessageBuilder();
Message message = builder.parseMessage(new ByteArrayInputStream(mimeBytes));
Message message = relayMessage.message();
if (message == null) {
LOG.warnv("SMTP raw relay skipped (message could not be parsed) for from={0}, messageId={1}",
relayMessage.from(), relayMessage.messageId());
return;
}
MailMessage mail = new MailMessage();
@@ -465,6 +475,10 @@ public class SmtpRelay {
} catch (TimeoutException e) {
LOG.warnv("SMTP raw relay timed out after {0}s for from={1}",
RELAY_TIMEOUT_SECONDS, relayMessage.from());
} catch (StackOverflowError e) {
// A message can nest shallowly enough to parse and still overflow the writer that
// re-serializes its embedded messages; the trace is thousands of identical frames.
LOG.warnv("SMTP raw relay skipped (message nested too deeply) for from={0}", relayMessage.from());
} catch (Exception e) {
LOG.warnv(e, "SMTP raw relay failed for from={0}", relayMessage.from());
}
@@ -2,12 +2,15 @@ package io.floci.aws.services.ses.mime;
import org.apache.james.mime4j.dom.Message;
import org.apache.james.mime4j.message.DefaultMessageBuilder;
import org.jboss.logging.Logger;
import java.io.ByteArrayInputStream;
/** The lenient MIME parse the send path runs once and shares between header extraction and the content scan. */
public final class SesMimeParser {
private static final Logger LOG = Logger.getLogger(SesMimeParser.class);
private SesMimeParser() {
}
@@ -15,9 +18,11 @@ public final class SesMimeParser {
public static Message parse(byte[] mimeBytes) {
try {
return new DefaultMessageBuilder().parseMessage(new ByteArrayInputStream(mimeBytes));
} catch (Exception | StackOverflowError ignored) {
// The caller treats an unparseable message as such; there is nothing to diagnose here,
// and mime4j nests a reader per forwarded message, so a hostile depth overflows too.
} catch (Exception | StackOverflowError e) {
// The caller treats an unparseable message as such, so the reason is only worth a debug
// line. mime4j nests a reader per forwarded message, so a hostile depth overflows too;
// the throwable is named rather than attached because that trace is thousands of frames.
LOG.debugv("MIME message could not be parsed: {0}", e.toString());
return null;
}
}
@@ -307,7 +307,7 @@ class SesServiceSmtpTest {
SmtpRelay.RawRelayMessage relayed = capturedRawRelay();
assertEquals("from@example.com", relayed.from());
assertEquals(List.of("to@example.com"), relayed.destinations());
assertEquals("raw MIME", relayed.rawMessage());
assertNotNull(relayed.message());
assertEquals(messageId, relayed.messageId());
}
@@ -1,5 +1,6 @@
package io.floci.aws.services.ses;
import io.floci.aws.services.ses.mime.NestedMime;
import io.floci.aws.services.ses.mime.SesMimeParser;
import io.floci.aws.services.ses.model.MessageAttachment;
import io.floci.aws.services.ses.model.MessageHeader;
@@ -325,6 +326,28 @@ class SmtpRelayTest {
List.of("to@example.com"), "Subject: X\r\n\r\nBody")));
}
@Test
void relayRaw_nestingThatOverflowsTheParser_isSkippedNotThrown() {
SmtpRelay relay = new SmtpRelay(mailClient, true);
String rawMime = NestedMime.rfc822Layers(NestedMime.OVERFLOWS_THE_PARSER);
assertDoesNotThrow(() -> relay.relayRaw(raw("from@example.com", List.of("to@example.com"), rawMime)));
verify(mailClient, never()).sendMail(any(MailMessage.class));
}
@Test
void relayRaw_nestingThatParsesButOverflowsTheWriter_isSkippedNotThrown() {
SmtpRelay relay = new SmtpRelay(mailClient, true);
SmtpRelay.RawRelayMessage nested = raw("from@example.com", List.of("to@example.com"),
NestedMime.rfc822Layers(NestedMime.OVERFLOWS_THE_WRITER));
assertNotNull(nested.message());
assertDoesNotThrow(() -> relay.relayRaw(nested));
verify(mailClient, never()).sendMail(any(MailMessage.class));
}
@Test
void parseRawRecipients_extractsToCcBcc() {
String raw = "From: sender@example.com\r\n"
@@ -0,0 +1,18 @@
package io.floci.aws.services.ses.mime;
/** Builds messages wrapped in {@code message/rfc822} layers, for the depth limits of mime4j. */
public final class NestedMime {
/** Deep enough that mime4j, which nests a reader per forwarded message, overflows the stack parsing it. */
public static final int OVERFLOWS_THE_PARSER = 100_000;
/** Shallow enough to parse, too deep for the writer that re-serializes embedded messages. */
public static final int OVERFLOWS_THE_WRITER = 10_000;
private NestedMime() {
}
public static String rfc822Layers(int depth) {
return "Content-Type: message/rfc822\r\n\r\n".repeat(depth) + "Content-Type: text/plain\r\n\r\nbody\r\n";
}
}
@@ -22,9 +22,7 @@ class SesMimeParserTest {
@Test
void nestingThatOverflowsTheParserIsNullNotAnError() {
// mime4j nests a reader per forwarded message and overflows the stack at this depth.
String layer = "Content-Type: message/rfc822\r\n\r\n";
byte[] mime = (layer.repeat(100_000) + "Content-Type: text/plain\r\n\r\nbody\r\n")
byte[] mime = NestedMime.rfc822Layers(NestedMime.OVERFLOWS_THE_PARSER)
.getBytes(StandardCharsets.US_ASCII);
assertNull(SesMimeParser.parse(mime));