From 57e4859f32b9d8519199445a7ab22872feb83d0c Mon Sep 17 00:00:00 2001 From: Kenshin Okinaka Date: Fri, 20 Nov 2026 00:12:56 +0900 Subject: [PATCH] refactor(ses): move the content scan into the mime package (#8986) --- .../io/floci/aws/services/ses/SesService.java | 4 +- .../io/floci/aws/services/ses/SmtpRelay.java | 14 +----- .../ses/{ => mime}/SesContentScan.java | 22 +++------ .../aws/services/ses/mime/SesMimeParser.java | 24 ++++++++++ ...icationEmailTemplateV2IntegrationTest.java | 3 +- .../SesEventPublishingV2IntegrationTest.java | 9 ++-- .../SesMessageInsightsV2IntegrationTest.java | 3 +- .../aws/services/ses/SesServiceSmtpTest.java | 9 ++-- ...SesSimpleAttachmentsV2IntegrationTest.java | 6 ++- .../floci/aws/services/ses/SmtpRelayTest.java | 3 +- .../ses/{ => mime}/SesContentScanTest.java | 45 ++++++++++--------- .../services/ses/mime/SesMimeParserTest.java | 37 +++++++++++++++ .../services/ses/mime/SesTestSignature.java | 15 +++++++ 13 files changed, 133 insertions(+), 61 deletions(-) rename src/main/java/io/floci/aws/services/ses/{ => mime}/SesContentScan.java (94%) create mode 100644 src/main/java/io/floci/aws/services/ses/mime/SesMimeParser.java rename src/test/java/io/floci/aws/services/ses/{ => mime}/SesContentScanTest.java (89%) create mode 100644 src/test/java/io/floci/aws/services/ses/mime/SesMimeParserTest.java create mode 100644 src/test/java/io/floci/aws/services/ses/mime/SesTestSignature.java diff --git a/src/main/java/io/floci/aws/services/ses/SesService.java b/src/main/java/io/floci/aws/services/ses/SesService.java index 0df2087fd0..31b66ee5c1 100644 --- a/src/main/java/io/floci/aws/services/ses/SesService.java +++ b/src/main/java/io/floci/aws/services/ses/SesService.java @@ -10,6 +10,8 @@ import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.services.ses.address.SesAddressLength; import io.floci.aws.services.ses.address.SesAddressSyntax; +import io.floci.aws.services.ses.mime.SesContentScan; +import io.floci.aws.services.ses.mime.SesMimeParser; import io.floci.aws.services.ses.model.BulkEmailEntry; import io.floci.aws.services.ses.model.BulkEmailEntryResult; import io.floci.aws.services.ses.model.ConfigurationSet; @@ -450,7 +452,7 @@ public class SesService { if (content.hasAttachments()) { mime = SmtpRelay.encodeMime(simpleRelayMessage(request, content, effectiveReturnPath, messageId, request.toAddresses(), request.ccAddresses(), null)); - Message parsedMime = SmtpRelay.parseMime(mime); + Message parsedMime = SesMimeParser.parse(mime); rejectBlockedAttachments(parsedMime); SesContentScan.Result scan = SesContentScan.scan(mime, parsedMime); if (scan == SesContentScan.Result.UNREADABLE) { diff --git a/src/main/java/io/floci/aws/services/ses/SmtpRelay.java b/src/main/java/io/floci/aws/services/ses/SmtpRelay.java index ac4b2591de..59fd8b39de 100644 --- a/src/main/java/io/floci/aws/services/ses/SmtpRelay.java +++ b/src/main/java/io/floci/aws/services/ses/SmtpRelay.java @@ -1,6 +1,7 @@ package io.floci.aws.services.ses; import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.services.ses.mime.SesMimeParser; import io.floci.aws.services.ses.model.MessageAttachment; import io.floci.aws.services.ses.model.MessageHeader; import io.floci.aws.services.ses.model.MessageTag; @@ -729,22 +730,11 @@ public class SmtpRelay { return new ParsedRawMessage(new byte[0], null, RawMessageHeaders.empty()); } byte[] mimeBytes = tryBase64Decode(rawMessage); - Message message = parseMime(mimeBytes); + Message message = SesMimeParser.parse(mimeBytes); return new ParsedRawMessage(mimeBytes, message, message == null ? RawMessageHeaders.empty() : headersOf(message)); } - /** Parses MIME bytes, or returns {@code null} for anything the parser cannot read. */ - static Message parseMime(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. - return null; - } - } - private static RawMessageHeaders headersOf(Message message) { try { String subject = message.getSubject() != null ? message.getSubject() : ""; diff --git a/src/main/java/io/floci/aws/services/ses/SesContentScan.java b/src/main/java/io/floci/aws/services/ses/mime/SesContentScan.java similarity index 94% rename from src/main/java/io/floci/aws/services/ses/SesContentScan.java rename to src/main/java/io/floci/aws/services/ses/mime/SesContentScan.java index dfa07deac7..d801948a75 100644 --- a/src/main/java/io/floci/aws/services/ses/SesContentScan.java +++ b/src/main/java/io/floci/aws/services/ses/mime/SesContentScan.java @@ -1,4 +1,4 @@ -package io.floci.aws.services.ses; +package io.floci.aws.services.ses.mime; import org.apache.james.mime4j.codec.DecodeMonitor; import org.apache.james.mime4j.codec.DecoderUtil; @@ -32,7 +32,7 @@ import java.util.Set; * logged, and is exposed to tests only through {@link #signature()} so no test source carries it * either. A message that trips the scan is likewise never persisted with its body. */ -final class SesContentScan { +public final class SesContentScan { private static final Logger LOG = Logger.getLogger(SesContentScan.class); @@ -68,12 +68,12 @@ final class SesContentScan { } /** True when any of the given texts carries the test signature. Nulls are skipped. */ - static boolean containsTestVirus(String... texts) { + public static boolean containsTestVirus(String... texts) { return containsTestVirus(Arrays.asList(texts)); } /** True when any of the given texts carries the test signature. Nulls are skipped. */ - static boolean containsTestVirus(Iterable texts) { + public static boolean containsTestVirus(Iterable texts) { for (String text : texts) { if (text != null && text.contains(SIGNATURE_TEXT)) { return true; @@ -83,7 +83,7 @@ final class SesContentScan { } /** The outcome of scanning a raw message. */ - enum Result { + public enum Result { CLEAN, REJECTED, /** The parser could not read the message, so only the wire bytes were checked. */ @@ -91,7 +91,7 @@ final class SesContentScan { } /** Scans a raw message from its wire bytes and the parse of them, {@code null} when it failed. */ - static Result scan(byte[] mime, Message parsed) { + public static Result scan(byte[] mime, Message parsed) { if (mime == null || mime.length == 0) { return Result.CLEAN; } @@ -113,20 +113,12 @@ final class SesContentScan { } } - /** Scans a raw message, parsing it first; the parse is shared with the send path elsewhere. */ - static Result scan(byte[] mime) { - if (mime == null || mime.length == 0) { - return Result.CLEAN; - } - return scan(mime, SmtpRelay.parseMime(mime)); - } - /** * True when any part of the parsed message, forwarded messages included, carries a file name * whose extension SES refuses. The name is read from {@code Content-Disposition} and, failing * that, from the {@code name} parameter of {@code Content-Type}. */ - static boolean hasBlockedAttachment(Message parsed) { + public static boolean hasBlockedAttachment(Message parsed) { if (parsed == null) { return false; } diff --git a/src/main/java/io/floci/aws/services/ses/mime/SesMimeParser.java b/src/main/java/io/floci/aws/services/ses/mime/SesMimeParser.java new file mode 100644 index 0000000000..cede10361f --- /dev/null +++ b/src/main/java/io/floci/aws/services/ses/mime/SesMimeParser.java @@ -0,0 +1,24 @@ +package io.floci.aws.services.ses.mime; + +import org.apache.james.mime4j.dom.Message; +import org.apache.james.mime4j.message.DefaultMessageBuilder; + +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 SesMimeParser() { + } + + /** Parses MIME bytes, or returns {@code null} for anything the parser cannot read. */ + 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. + return null; + } + } +} diff --git a/src/test/java/io/floci/aws/services/ses/SesCustomVerificationEmailTemplateV2IntegrationTest.java b/src/test/java/io/floci/aws/services/ses/SesCustomVerificationEmailTemplateV2IntegrationTest.java index 1618b5641b..e696beabb7 100644 --- a/src/test/java/io/floci/aws/services/ses/SesCustomVerificationEmailTemplateV2IntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ses/SesCustomVerificationEmailTemplateV2IntegrationTest.java @@ -1,5 +1,6 @@ package io.floci.aws.services.ses; +import io.floci.aws.services.ses.mime.SesTestSignature; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; @@ -163,7 +164,7 @@ class SesCustomVerificationEmailTemplateV2IntegrationTest { void sendWithTemplateCarryingTheTestSignature_isRecordedWithoutItsBodyAndNotRelayed() { // The signature comes from the scanner so it never appears in test source; the JSON needs // its one backslash escaped. - String content = SesContentScan.signature().replace("\\", "\\\\"); + String content = SesTestSignature.value().replace("\\", "\\\\"); given().contentType("application/json").header("Authorization", AUTH) .body(""" {"TemplateName": "cvet-v2-scan", "FromEmailAddress": "%s", "TemplateSubject": "scan", diff --git a/src/test/java/io/floci/aws/services/ses/SesEventPublishingV2IntegrationTest.java b/src/test/java/io/floci/aws/services/ses/SesEventPublishingV2IntegrationTest.java index cc68dfdd81..142524eadd 100644 --- a/src/test/java/io/floci/aws/services/ses/SesEventPublishingV2IntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ses/SesEventPublishingV2IntegrationTest.java @@ -7,6 +7,7 @@ import io.floci.aws.services.cloudwatch.metrics.CloudWatchMetricsService.MetricI import io.floci.aws.services.firehose.FirehoseService; import io.floci.aws.services.s3.S3Service; import io.floci.aws.services.s3.model.S3Object; +import io.floci.aws.services.ses.mime.SesTestSignature; import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; import io.restassured.response.Response; @@ -1673,7 +1674,7 @@ class SesEventPublishingV2IntegrationTest { void eicarAttachment_isAcceptedThenRejected() throws Exception { // The signature comes from the scanner itself so it never appears in test source. String encoded = Base64.getEncoder().encodeToString( - SesContentScan.signature().getBytes(StandardCharsets.US_ASCII)); + SesTestSignature.value().getBytes(StandardCharsets.US_ASCII)); String mime = "From: " + SENDER + "\r\nTo: success@simulator.amazonses.com\r\nSubject: scan\r\n" + "X-SES-MESSAGE-TAGS: probe=leak\r\n" + "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"b\"\r\n\r\n" @@ -1761,7 +1762,7 @@ class SesEventPublishingV2IntegrationTest { "Content": {"Simple": {"Subject": {"Data": "scan"}, "Body": {"Text": {"Data": "%s"}, "Html": {"Data": "

clean

"}}}}} - """.formatted(SENDER, CS, SesContentScan.signature().replace("\\", "\\\\"))) + """.formatted(SENDER, CS, SesTestSignature.value().replace("\\", "\\\\"))) .when().post("/v2/email/outbound-emails").then().statusCode(200) .extract().jsonPath().getString("MessageId"); @@ -1784,7 +1785,7 @@ class SesEventPublishingV2IntegrationTest { // A raw send is scanned as a whole, header block included, so the simple path has to // cover the subject and the caller's header names and values as well or the two paths // disagree; and the stored record keeps none of them. - String signature = SesContentScan.signature().replace("\\", "\\\\"); + String signature = SesTestSignature.value().replace("\\", "\\\\"); for (String content : new String[] { "\"Subject\": {\"Data\": \"" + signature + "\"}, \"Body\": {\"Text\": {\"Data\": \"clean\"}}", "\"Subject\": {\"Data\": \"clean\"}, \"Body\": {\"Text\": {\"Data\": \"clean\"}}, " @@ -1832,7 +1833,7 @@ class SesEventPublishingV2IntegrationTest { void customVerificationEmail_publishesThroughTheSameClassifierAsAnyOtherSend() throws Exception { // SendCustomVerificationEmail accepts a ConfigurationSetName like the other send APIs, so a // clean verification email publishes a Send and one carrying the signature adds a Reject. - String signature = SesContentScan.signature().replace("\\", "\\\\"); + String signature = SesTestSignature.value().replace("\\", "\\\\"); String recipient = "cvet-events@cvet-events.floci.test"; createCustomVerificationTemplate("cvet-events-clean", "

verify

"); createCustomVerificationTemplate("cvet-events-scan", "

" + signature + "

"); diff --git a/src/test/java/io/floci/aws/services/ses/SesMessageInsightsV2IntegrationTest.java b/src/test/java/io/floci/aws/services/ses/SesMessageInsightsV2IntegrationTest.java index 80b9cf629e..44d1e382f9 100644 --- a/src/test/java/io/floci/aws/services/ses/SesMessageInsightsV2IntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ses/SesMessageInsightsV2IntegrationTest.java @@ -1,5 +1,6 @@ package io.floci.aws.services.ses; +import io.floci.aws.services.ses.mime.SesTestSignature; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; @@ -290,7 +291,7 @@ class SesMessageInsightsV2IntegrationTest { String raw = "From: " + SENDER + "\r\nTo: raw@example.com\r\n" + "Subject: rejected-mime-subject\r\n" + SmtpRelay.HEADER_MESSAGE_TAGS + ": campaign=fromheader\r\n\r\n" - + SesContentScan.signature() + "\r\n"; + + SesTestSignature.value() + "\r\n"; String messageId = given().contentType("application/json").header("Authorization", AUTH) .body(""" {"FromEmailAddress": "%s", diff --git a/src/test/java/io/floci/aws/services/ses/SesServiceSmtpTest.java b/src/test/java/io/floci/aws/services/ses/SesServiceSmtpTest.java index 01eea1ebe4..15abbe7cd1 100644 --- a/src/test/java/io/floci/aws/services/ses/SesServiceSmtpTest.java +++ b/src/test/java/io/floci/aws/services/ses/SesServiceSmtpTest.java @@ -2,6 +2,7 @@ package io.floci.aws.services.ses; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.services.ses.mime.SesTestSignature; import io.floci.aws.services.ses.model.ConfigurationSet; import io.floci.aws.services.ses.model.CustomVerificationEmailTemplate; import io.floci.aws.services.ses.model.EmailContent; @@ -66,7 +67,7 @@ class SesServiceSmtpTest { @Test void sendCustomVerificationEmail_signatureInTheTemplateSubject_isRejectedAndNotRelayed() { // The scan covers the subject as well as the content, and neither reaches the relay. - cvetTemplate("cvet-subject", SesContentScan.signature(), "

clean

"); + cvetTemplate("cvet-subject", SesTestSignature.value(), "

clean

"); String messageId = service.sendCustomVerificationEmail("target@example.com", "cvet-subject", null, "us-east-1"); @@ -78,7 +79,7 @@ class SesServiceSmtpTest { @Test void sendCustomVerificationEmail_signatureInTheTemplateContent_isRejectedAndNotRelayed() { - cvetTemplate("cvet-content", "clean", "

" + SesContentScan.signature() + "

"); + cvetTemplate("cvet-content", "clean", "

" + SesTestSignature.value() + "

"); String messageId = service.sendCustomVerificationEmail("target@example.com", "cvet-content", null, "us-east-1"); @@ -186,7 +187,7 @@ class SesServiceSmtpTest { .toAddresses(List.of("to@example.com")) .region("us-east-1") .content(new EmailContent.Simple("Subject", "clean", null, List.of(), - List.of(pdfAttachment(SesContentScan.signature().getBytes(StandardCharsets.US_ASCII))))) + List.of(pdfAttachment(SesTestSignature.value().getBytes(StandardCharsets.US_ASCII))))) .build()); SentEmail stored = storedEmail(messageId); @@ -261,7 +262,7 @@ class SesServiceSmtpTest { identities.verifyEmailIdentity("bounces@example.com", "us-east-1"); identities.verifyEmailIdentity("bounces@evil.example", "us-east-1"); String raw = "From: from@example.com\r\nTo: to@example.com\r\nReturn-Path: \r\n" - + "Subject: " + SesContentScan.signature() + "\r\n\r\nbody\r\n"; + + "Subject: " + SesTestSignature.value() + "\r\n\r\nbody\r\n"; String messageId = service.sendEmail(SendEmailRequest.builder() .source("from@example.com") diff --git a/src/test/java/io/floci/aws/services/ses/SesSimpleAttachmentsV2IntegrationTest.java b/src/test/java/io/floci/aws/services/ses/SesSimpleAttachmentsV2IntegrationTest.java index 1022ad24ce..78f79bf333 100644 --- a/src/test/java/io/floci/aws/services/ses/SesSimpleAttachmentsV2IntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ses/SesSimpleAttachmentsV2IntegrationTest.java @@ -1,5 +1,7 @@ package io.floci.aws.services.ses; +import io.floci.aws.services.ses.mime.SesMimeParser; +import io.floci.aws.services.ses.mime.SesTestSignature; import io.quarkus.test.junit.QuarkusTest; import io.restassured.path.json.JsonPath; import io.restassured.response.Response; @@ -96,7 +98,7 @@ class SesSimpleAttachmentsV2IntegrationTest { assertTrue(wire.contains("X-Custom: custom-value"), wire); assertFalse(wire.contains("hidden@example.com"), "Bcc must not appear in the message"); - Message message = SmtpRelay.parseMime(mime); + Message message = SesMimeParser.parse(mime); assertNotNull(message); assertEquals("With attachments", message.getSubject()); List leaves = new ArrayList<>(); @@ -144,7 +146,7 @@ class SesSimpleAttachmentsV2IntegrationTest { @Test @Order(4) void simpleSend_withVirusInAnAttachment_isRejectedLikeARawSend() { - String virus = b64(SesContentScan.signature().getBytes(StandardCharsets.US_ASCII)); + String virus = b64(SesTestSignature.value().getBytes(StandardCharsets.US_ASCII)); String messageId = send(""" {"FromEmailAddress": "%s", "Destination": {"ToAddresses": ["to@example.com"]}, diff --git a/src/test/java/io/floci/aws/services/ses/SmtpRelayTest.java b/src/test/java/io/floci/aws/services/ses/SmtpRelayTest.java index 8e34094990..2d8f28d3ed 100644 --- a/src/test/java/io/floci/aws/services/ses/SmtpRelayTest.java +++ b/src/test/java/io/floci/aws/services/ses/SmtpRelayTest.java @@ -1,5 +1,6 @@ package io.floci.aws.services.ses; +import io.floci.aws.services.ses.mime.SesMimeParser; import io.floci.aws.services.ses.model.MessageAttachment; import io.floci.aws.services.ses.model.MessageHeader; import io.floci.aws.services.ses.model.MessageTag; @@ -902,6 +903,6 @@ class SmtpRelayTest { assertTrue(text.contains("Message-ID: "), text); assertEquals(text.indexOf("Message-ID:"), text.lastIndexOf("Message-ID:"), text); assertFalse(text.contains("hidden@example.com"), text); - assertNotNull(SmtpRelay.parseMime(mime)); + assertNotNull(SesMimeParser.parse(mime)); } } diff --git a/src/test/java/io/floci/aws/services/ses/SesContentScanTest.java b/src/test/java/io/floci/aws/services/ses/mime/SesContentScanTest.java similarity index 89% rename from src/test/java/io/floci/aws/services/ses/SesContentScanTest.java rename to src/test/java/io/floci/aws/services/ses/mime/SesContentScanTest.java index 43dde39d79..bb26e3ea26 100644 --- a/src/test/java/io/floci/aws/services/ses/SesContentScanTest.java +++ b/src/test/java/io/floci/aws/services/ses/mime/SesContentScanTest.java @@ -1,6 +1,6 @@ -package io.floci.aws.services.ses; +package io.floci.aws.services.ses.mime; -import io.floci.aws.services.ses.SesContentScan.Result; +import io.floci.aws.services.ses.mime.SesContentScan.Result; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; @@ -40,7 +40,7 @@ class SesContentScanTest { void signatureInsideAPlainMimeBodyIsFlagged() { String mime = "From: a@example.com\r\nTo: b@example.com\r\nSubject: x\r\n\r\n" + SIGNATURE + "\r\n"; - assertEquals(Result.REJECTED, SesContentScan.scan(mime.getBytes(StandardCharsets.UTF_8))); + assertEquals(Result.REJECTED, scan(mime.getBytes(StandardCharsets.UTF_8))); } @Test @@ -58,7 +58,7 @@ class SesContentScanTest { assertFalse(new String(bytes, StandardCharsets.ISO_8859_1).contains(SIGNATURE), "the fixture must only carry the signature in encoded form"); - assertEquals(Result.REJECTED, SesContentScan.scan(bytes)); + assertEquals(Result.REJECTED, scan(bytes)); } @Test @@ -76,7 +76,7 @@ class SesContentScanTest { assertFalse(new String(bytes, StandardCharsets.ISO_8859_1).contains(SIGNATURE), "the fixture must only carry the signature in encoded form"); - assertEquals(Result.REJECTED, SesContentScan.scan(bytes)); + assertEquals(Result.REJECTED, scan(bytes)); } @Test @@ -114,7 +114,7 @@ class SesContentScanTest { assertFalse(new String(bytes, StandardCharsets.ISO_8859_1).contains(SIGNATURE), "the fixture must only carry the signature in encoded form"); - assertEquals(Result.REJECTED, SesContentScan.scan(bytes)); + assertEquals(Result.REJECTED, scan(bytes)); } @Test @@ -130,7 +130,7 @@ class SesContentScanTest { assertFalse(new String(bytes, StandardCharsets.ISO_8859_1).contains(SIGNATURE), "the fixture must only carry the signature in encoded form"); - assertEquals(Result.REJECTED, SesContentScan.scan(bytes)); + assertEquals(Result.REJECTED, scan(bytes)); } @Test @@ -140,7 +140,7 @@ class SesContentScanTest { String encoded = Base64.getEncoder().encodeToString(SIGNATURE.getBytes(StandardCharsets.US_ASCII)); String mime = "From: a@example.com\r\nX-Probe: " + encoded + "\r\n\r\n" + encoded + "\r\n"; - assertEquals(Result.CLEAN, SesContentScan.scan(mime.getBytes(StandardCharsets.US_ASCII))); + assertEquals(Result.CLEAN, scan(mime.getBytes(StandardCharsets.US_ASCII))); } @Test @@ -151,7 +151,7 @@ class SesContentScanTest { + "--b\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: base64\r\n\r\n" + encoded + "\r\n--b--\r\n"; - assertEquals(Result.REJECTED, SesContentScan.scan(mime.getBytes(StandardCharsets.US_ASCII))); + assertEquals(Result.REJECTED, scan(mime.getBytes(StandardCharsets.US_ASCII))); } @Test @@ -159,14 +159,14 @@ class SesContentScanTest { byte[] bytes = nestedForwards(3_000); assertFalse(new String(bytes, StandardCharsets.ISO_8859_1).contains(SIGNATURE)); - assertEquals(Result.REJECTED, SesContentScan.scan(bytes)); + assertEquals(Result.REJECTED, scan(bytes)); } @Test void nestingBeyondTheParserIsRefusedNotCrashed() { // mime4j nests a reader per forwarded message and overflows the stack at this depth; the // scan must say so rather than throw an Error or call the message clean. - assertEquals(Result.UNREADABLE, SesContentScan.scan(nestedForwards(100_000))); + assertEquals(Result.UNREADABLE, scan(nestedForwards(100_000))); } // message/rfc822 layers around a quoted-printable copy of the signature, so nothing on the @@ -185,7 +185,7 @@ class SesContentScanTest { void base64OfCleanContentIsNotFlagged() { byte[] blob = Base64.getMimeEncoder().encode("nothing to see here, just a long enough clean payload".getBytes(StandardCharsets.US_ASCII)); - assertEquals(Result.CLEAN, SesContentScan.scan(blob)); + assertEquals(Result.CLEAN, scan(blob)); } @Test @@ -197,7 +197,7 @@ class SesContentScanTest { + "--b\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: base64\r\n\r\n" + encoded + "\r\n--b--\r\n"; - assertEquals(Result.CLEAN, SesContentScan.scan(mime.getBytes(StandardCharsets.UTF_8))); + assertEquals(Result.CLEAN, scan(mime.getBytes(StandardCharsets.UTF_8))); } @Test @@ -208,13 +208,13 @@ class SesContentScanTest { bytes[1] = 1; System.arraycopy(signature, 0, bytes, 2, signature.length); - assertEquals(Result.REJECTED, SesContentScan.scan(bytes)); + assertEquals(Result.REJECTED, scan(bytes)); } @Test void emptyInputIsNotFlagged() { - assertEquals(Result.CLEAN, SesContentScan.scan(new byte[0])); - assertEquals(Result.CLEAN, SesContentScan.scan((byte[]) null)); + assertEquals(Result.CLEAN, scan(new byte[0])); + assertEquals(Result.CLEAN, scan(null)); } // Escapes the characters of the signature that quoted-printable may encode, and soft-wraps, @@ -244,11 +244,11 @@ class SesContentScanTest { @Test void attachmentNamedByDispositionOrContentTypeIsBlocked() { - assertTrue(SesContentScan.hasBlockedAttachment(SmtpRelay.parseMime( + assertTrue(SesContentScan.hasBlockedAttachment(SesMimeParser.parse( multipart("Content-Disposition: attachment; filename=\"tool.exe\"\r\n")))); - assertTrue(SesContentScan.hasBlockedAttachment(SmtpRelay.parseMime( + assertTrue(SesContentScan.hasBlockedAttachment(SesMimeParser.parse( multipart("Content-Type: application/octet-stream; name=\"macro.vbs\"\r\n")))); - assertFalse(SesContentScan.hasBlockedAttachment(SmtpRelay.parseMime( + assertFalse(SesContentScan.hasBlockedAttachment(SesMimeParser.parse( multipart("Content-Disposition: attachment; filename=\"report.pdf\"\r\n")))); } @@ -260,7 +260,12 @@ class SesContentScanTest { + "MIME-Version: 1.0\r\nContent-Type: message/rfc822\r\n\r\n" + inner; assertTrue(SesContentScan.hasBlockedAttachment( - SmtpRelay.parseMime(outer.getBytes(StandardCharsets.US_ASCII)))); + SesMimeParser.parse(outer.getBytes(StandardCharsets.US_ASCII)))); + } + + // The send path parses once and hands the parse to the scan; these cases do the same. + private static Result scan(byte[] mime) { + return SesContentScan.scan(mime, mime == null ? null : SesMimeParser.parse(mime)); } private static byte[] multipart(String attachmentHeaders) { diff --git a/src/test/java/io/floci/aws/services/ses/mime/SesMimeParserTest.java b/src/test/java/io/floci/aws/services/ses/mime/SesMimeParserTest.java new file mode 100644 index 0000000000..aa55c7c395 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ses/mime/SesMimeParserTest.java @@ -0,0 +1,37 @@ +package io.floci.aws.services.ses.mime; + +import org.apache.james.mime4j.dom.Message; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +class SesMimeParserTest { + + @Test + void readableMessageIsParsed() { + Message message = SesMimeParser.parse( + "From: a@example.com\r\nSubject: hello\r\n\r\nbody\r\n".getBytes(StandardCharsets.US_ASCII)); + + assertNotNull(message); + assertEquals("hello", message.getSubject()); + } + + @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") + .getBytes(StandardCharsets.US_ASCII); + + assertNull(SesMimeParser.parse(mime)); + } + + @Test + void nullInputIsNull() { + assertNull(SesMimeParser.parse(null)); + } +} diff --git a/src/test/java/io/floci/aws/services/ses/mime/SesTestSignature.java b/src/test/java/io/floci/aws/services/ses/mime/SesTestSignature.java new file mode 100644 index 0000000000..8ee1dc4a70 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ses/mime/SesTestSignature.java @@ -0,0 +1,15 @@ +package io.floci.aws.services.ses.mime; + +/** + * Hands the content scan's test signature to tests outside this package, so the accessor on + * {@link SesContentScan} stays package-private and no test source spells the string out. + */ +public final class SesTestSignature { + + private SesTestSignature() { + } + + public static String value() { + return SesContentScan.signature(); + } +}