From c69580764ebf2501f8cec63b4002dcfa822b3332 Mon Sep 17 00:00:00 2001 From: Kenshin Okinaka Date: Tue, 21 Apr 2026 12:47:06 +0900 Subject: [PATCH] feat(ses): SMTP relay for SendEmail and SendRawEmail (#534) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(ses): add SMTP relay configuration to EmulatorConfig Add smtp-host, smtp-port, smtp-user, smtp-pass, and smtp-starttls settings to SesServiceConfig. smtp-host is Optional — when absent or empty, relay is disabled and emails are stored only (existing behavior). * feat(ses): implement SMTP relay with Vert.x MailClient and Mime4j Add SmtpRelay that forwards SES emails to a configured SMTP server using a dedicated Vert.x MailClient built from EmulatorConfig settings. Simple emails are sent as MailMessage with From/To/Cc/Bcc/ReplyTo/ Subject/Text/Html. Raw MIME emails are parsed with Apache Mime4j to extract headers and body, then sent via the same MailClient. When SES Destinations is provided, it is used as the authoritative envelope recipient list (MIME Cc headers do not add extra SMTP recipients). Relay is dispatched asynchronously on a dedicated daemon thread with a 30-second send timeout. Failures are logged with stack traces but never affect the API response. The executor and MailClient are only created when smtp-host is configured and ses.enabled is true, and shut down in @PreDestroy. SesService calls SmtpRelay.relay/relayRaw after storing emails so the inspection endpoint always has the data regardless of relay. Tests: SmtpRelayTest (12 cases) covers simple/raw relay, disabled path, error swallowing, base64 decoding, HTML content type, envelope fallback. SesServiceSmtpTest (5 cases) verifies relay integration and store persistence. * docs(ses): document SMTP relay configuration Add SMTP Relay section to docs/services/ses.md with configuration example, docker-compose snippet with Mailpit, and behavioral notes. Add SMTP settings to the YAML sample and environment variable table in docs/configuration/application-yml.md. * fix(ses): preserve body against attachment overwrite and extract Bcc from raw MIME - extractBodyFromEntity now only sets text/html when not already set, so a text-typed attachment in multipart/mixed cannot clobber the body picked up from multipart/alternative. - doRelayRaw now reads Bcc from MIME headers alongside To/Cc when the caller did not supply Destinations. * fix(ses): initialize Vert.x NTLMEngineImpl at run time for native image The vertx-mail-client dependency brings in io.vertx.ext.mail.impl.sasl.NTLMEngineImpl, whose static state embeds a SecureRandom instance. GraalVM native-image rejects build-time Random/SecureRandom objects because the cached seed makes runtime behavior unpredictable. Mark the class for run-time initialization, matching the existing entry for the Apache HttpClient NTLM engine. --- docs/configuration/application-yml.md | 10 + docs/services/ses.md | 75 ++++- pom.xml | 11 + .../floci/config/EmulatorConfig.java | 17 + .../floci/services/ses/SesService.java | 13 +- .../floci/services/ses/SmtpRelay.java | 296 ++++++++++++++++++ src/main/resources/application.yml | 6 + .../services/ses/SesServiceSmtpTest.java | 98 ++++++ .../floci/services/ses/SmtpRelayTest.java | 278 ++++++++++++++++ 9 files changed, 791 insertions(+), 13 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/ses/SmtpRelay.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ses/SmtpRelayTest.java diff --git a/docs/configuration/application-yml.md b/docs/configuration/application-yml.md index 33e988dc84..8271e18349 100644 --- a/docs/configuration/application-yml.md +++ b/docs/configuration/application-yml.md @@ -164,6 +164,11 @@ floci: ses: enabled: true + # smtp-host: mailpit # SMTP server for email relay (empty = store only) + # smtp-port: 1025 + # smtp-user: "" + # smtp-pass: "" + # smtp-starttls: DISABLED # DISABLED, OPTIONAL, or REQUIRED opensearch: enabled: true @@ -226,6 +231,11 @@ All keys in this table are declared on `EmulatorConfig` and accept environment v | `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` | `false` | Enforce IAM identity-based policies on every request when `true` | | `FLOCI_SERVICES_OPENSEARCH_MOCK` | `false` | Skip Docker; domains appear active immediately (useful for CI) | | `FLOCI_SERVICES_OPENSEARCH_KEEP_RUNNING_ON_SHUTDOWN` | `false` | Leave OpenSearch containers running after Floci stops | +| `FLOCI_SERVICES_SES_SMTP_HOST` | *(unset)* | SMTP server host for SES email relay (empty = store only) | +| `FLOCI_SERVICES_SES_SMTP_PORT` | `25` | SMTP server port | +| `FLOCI_SERVICES_SES_SMTP_USER` | *(unset)* | SMTP authentication username | +| `FLOCI_SERVICES_SES_SMTP_PASS` | *(unset)* | SMTP authentication password | +| `FLOCI_SERVICES_SES_SMTP_STARTTLS` | `DISABLED` | STARTTLS mode: `DISABLED`, `OPTIONAL`, or `REQUIRED` | Per-queue SQS redrive policy (`maxReceiveCount`) is configured at queue creation time via `SetQueueAttributes` / `CreateQueue`, not as a global default. diff --git a/docs/services/ses.md b/docs/services/ses.md index 31051ff976..d904836ee2 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -33,8 +33,71 @@ floci: services: ses: enabled: true + # smtp-host: mailpit # SMTP server for email relay (empty = store only) + # smtp-port: 1025 + # smtp-user: "" + # smtp-pass: "" + # smtp-starttls: DISABLED # DISABLED, OPTIONAL, or REQUIRED ``` +### Environment Variables + +| Variable | Default | Description | +|---|---|---| +| `FLOCI_SERVICES_SES_ENABLED` | `true` | Enable or disable the SES service | +| `FLOCI_SERVICES_SES_SMTP_HOST` | *(unset)* | SMTP server host for email relay (empty = store only) | +| `FLOCI_SERVICES_SES_SMTP_PORT` | `25` | SMTP server port | +| `FLOCI_SERVICES_SES_SMTP_USER` | *(unset)* | SMTP authentication username | +| `FLOCI_SERVICES_SES_SMTP_PASS` | *(unset)* | SMTP authentication password | +| `FLOCI_SERVICES_SES_SMTP_STARTTLS` | `DISABLED` | STARTTLS mode: `DISABLED`, `OPTIONAL`, or `REQUIRED` | + +### 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. + +```yaml +# docker-compose.yml +services: + floci: + image: hectorvent/floci:latest + ports: ["4566:4566"] + environment: + FLOCI_SERVICES_SES_SMTP_HOST: mailpit + FLOCI_SERVICES_SES_SMTP_PORT: 1025 + networks: [floci] + + mailpit: + image: axllent/mailpit + ports: + - "8025:8025" # Web UI + - "1025:1025" # SMTP + networks: [floci] + +networks: + floci: +``` + +- 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. + +## Local Inspection Endpoint + +For test assertions and debugging, Floci exposes a LocalStack-compatible mailbox endpoint: + +- `GET /_aws/ses` lists captured messages +- `GET /_aws/ses?id=` returns a specific captured message +- `DELETE /_aws/ses` clears the captured mailbox + +Messages are stored locally by Floci and can be persisted when SES storage is backed by persistent or hybrid storage. + ## Examples ```bash @@ -76,23 +139,13 @@ aws ses send-raw-email \ curl $AWS_ENDPOINT_URL/_aws/ses ``` -## Local Inspection Endpoint - -For test assertions and debugging, Floci exposes a LocalStack-compatible mailbox endpoint: - -- `GET /_aws/ses` lists captured messages -- `GET /_aws/ses?id=` returns a specific captured message -- `DELETE /_aws/ses` clears the captured mailbox - -Messages are stored locally by Floci and can be persisted when SES storage is backed by persistent or hybrid storage. - ## Current Behavior - Identity verification succeeds immediately; no real DNS or inbox verification flow is required. - `SendEmail` stores the text body or the HTML body as the captured message body. - `SetIdentityNotificationTopic` stores SNS topic ARNs and returns them via `GetIdentityNotificationAttributes`. - Notification topics are configuration metadata only; SES delivery, bounce, or complaint events are not emitted automatically. -- SMTP submission is not implemented. For the REST JSON API see [SES v2](#v2) below. +- For the REST JSON API see [SES v2](#v2) below. ## SES v2 (REST JSON) {#v2} diff --git a/pom.xml b/pom.xml index 993900fe9a..e24ab5d618 100644 --- a/pom.xml +++ b/pom.xml @@ -48,6 +48,17 @@ io.quarkus quarkus-config-yaml + + + io.vertx + vertx-mail-client + + + + org.apache.james + apache-mime4j-dom + 0.8.11 + diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index a17f4a1e21..2eaf3c5c95 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -430,6 +430,23 @@ public interface EmulatorConfig { interface SesServiceConfig { @WithDefault("true") boolean enabled(); + + /** SMTP server host for email relay. Empty = relay disabled (emails stored only). */ + Optional smtpHost(); + + /** SMTP server port. */ + @WithDefault("25") + int smtpPort(); + + /** SMTP authentication username. Empty = no authentication. */ + Optional smtpUser(); + + /** SMTP authentication password. */ + Optional smtpPass(); + + /** STARTTLS mode: DISABLED, OPTIONAL, or REQUIRED. */ + @WithDefault("DISABLED") + String smtpStarttls(); } interface OpenSearchServiceConfig { diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java index 032941f323..b649df3b03 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java @@ -24,23 +24,27 @@ public class SesService { private final StorageBackend identityStore; private final StorageBackend emailStore; private final StorageBackend accountSettingsStore; + private final SmtpRelay smtpRelay; @Inject - public SesService(StorageFactory storageFactory) { + public SesService(StorageFactory storageFactory, SmtpRelay smtpRelay) { this.identityStore = storageFactory.create("ses", "ses-identities.json", new TypeReference>() {}); this.emailStore = storageFactory.create("ses", "ses-emails.json", new TypeReference>() {}); this.accountSettingsStore = storageFactory.create("ses", "ses-account-settings.json", new TypeReference>() {}); + this.smtpRelay = smtpRelay; } SesService(StorageBackend identityStore, StorageBackend emailStore, - StorageBackend accountSettingsStore) { + StorageBackend accountSettingsStore, + SmtpRelay smtpRelay) { this.identityStore = identityStore; this.emailStore = emailStore; this.accountSettingsStore = accountSettingsStore; + this.smtpRelay = smtpRelay; } public Identity verifyEmailIdentity(String emailAddress, String region) { @@ -128,6 +132,9 @@ public class SesService { bccAddresses, replyToAddresses, subject, bodyText, bodyHtml); emailStore.put("email::" + region + "::" + messageId, email); + smtpRelay.relay(source, toAddresses, ccAddresses, bccAddresses, + replyToAddresses, subject, bodyText, bodyHtml); + LOG.infov("SES email sent: from={0}, to={1}, subject={2}, messageId={3}", source, toAddresses, subject, messageId); return messageId; @@ -146,6 +153,8 @@ public class SesService { rawMessage); emailStore.put("email::" + region + "::" + messageId, email); + smtpRelay.relayRaw(source, destinations, rawMessage); + LOG.infov("SES raw email sent: from={0}, messageId={1}", source, messageId); return messageId; } diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SmtpRelay.java b/src/main/java/io/github/hectorvent/floci/services/ses/SmtpRelay.java new file mode 100644 index 0000000000..71e7153ebc --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SmtpRelay.java @@ -0,0 +1,296 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.vertx.ext.mail.MailClient; +import io.vertx.ext.mail.MailConfig; +import io.vertx.ext.mail.MailMessage; +import io.vertx.ext.mail.StartTLSOptions; +import jakarta.annotation.PreDestroy; +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.Multipart; +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.message.DefaultMessageBuilder; +import org.jboss.logging.Logger; + +import java.io.ByteArrayInputStream; +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.concurrent.AbstractExecutorService; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Optional SMTP relay for SES. When {@code floci.services.ses.smtp-host} + * is configured, sent emails are forwarded to the SMTP server in addition + * to being stored in the inspection endpoint. When unconfigured (or set + * to empty string), this class is a no-op. + * + *

Uses a dedicated Vert.x {@link MailClient} configured directly from + * {@link EmulatorConfig} rather than wiring through {@code quarkus.mailer.*}, + * which would crash on startup if the host property resolved to empty. + */ +@ApplicationScoped +public class SmtpRelay { + + private static final Logger LOG = Logger.getLogger(SmtpRelay.class); + private static final long RELAY_TIMEOUT_SECONDS = 30; + + private final MailClient mailClient; + private final ExecutorService relayExecutor; + private final boolean enabled; + + @Inject + public SmtpRelay(io.vertx.core.Vertx vertx, EmulatorConfig config) { + this.enabled = config.services().ses().enabled() + && config.services().ses().smtpHost() + .filter(h -> !h.isBlank()) + .isPresent(); + if (enabled) { + this.relayExecutor = Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r, "ses-smtp-relay"); + t.setDaemon(true); + return t; + }); + String host = config.services().ses().smtpHost().get(); + int port = config.services().ses().smtpPort(); + LOG.infov("SES SMTP relay enabled: {0}:{1}", host, 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); + } else { + this.relayExecutor = null; + this.mailClient = null; + } + } + + /** Package-private constructor for tests (synchronous executor, mock client). */ + SmtpRelay(MailClient mailClient, boolean enabled) { + this.mailClient = mailClient; + // Synchronous executor for deterministic test ordering + this.relayExecutor = new AbstractExecutorService() { + private volatile boolean shutdown = false; + @Override public void execute(Runnable r) { r.run(); } + @Override public void shutdown() { shutdown = true; } + @Override public java.util.List shutdownNow() { shutdown = true; return java.util.List.of(); } + @Override public boolean isShutdown() { return shutdown; } + @Override public boolean isTerminated() { return shutdown; } + @Override public boolean awaitTermination(long t, java.util.concurrent.TimeUnit u) { return true; } + }; + this.enabled = enabled; + } + + @PreDestroy + void shutdown() { + if (relayExecutor != null) { + relayExecutor.shutdownNow(); + } + if (mailClient != null) { + mailClient.close(); + } + } + + public boolean isEnabled() { + return enabled; + } + + /** + * Relays a structured email asynchronously. + */ + public void relay(String from, List toAddresses, List ccAddresses, + List bccAddresses, List replyToAddresses, + String subject, String bodyText, String bodyHtml) { + if (!enabled) { + return; + } + try { + relayExecutor.execute(() -> doRelay(from, toAddresses, ccAddresses, + bccAddresses, replyToAddresses, subject, bodyText, bodyHtml)); + } catch (java.util.concurrent.RejectedExecutionException e) { + LOG.warnv("SMTP relay skipped (executor shutting down) for from={0}", from); + } + } + + private void doRelay(String from, List toAddresses, List ccAddresses, + List bccAddresses, List replyToAddresses, + String subject, String bodyText, String bodyHtml) { + try { + MailMessage mail = new MailMessage(); + mail.setFrom(from); + if (toAddresses != null) { + mail.setTo(toAddresses); + } + if (ccAddresses != null) { + mail.setCc(ccAddresses); + } + if (bccAddresses != null) { + mail.setBcc(bccAddresses); + } + if (replyToAddresses != null && !replyToAddresses.isEmpty()) { + mail.addHeader("Reply-To", String.join(", ", replyToAddresses)); + } + mail.setSubject(subject != null ? subject : ""); + if (bodyText != null) { + mail.setText(bodyText); + } + if (bodyHtml != null) { + mail.setHtml(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); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOG.warnv(e, "SMTP relay interrupted for from={0}, to={1}", from, toAddresses); + } 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); + } catch (Exception e) { + LOG.warnv(e, "SMTP relay failed for from={0}, to={1}", from, toAddresses); + } + } + + /** + * Relays a raw MIME message. Parsed with Mime4j, then sent via MailClient. + */ + public void relayRaw(String from, List destinations, String rawMessage) { + if (!enabled) { + return; + } + try { + relayExecutor.execute(() -> doRelayRaw(from, destinations, rawMessage)); + } catch (java.util.concurrent.RejectedExecutionException e) { + LOG.warnv("SMTP raw relay skipped (executor shutting down) for from={0}", from); + } + } + + private void doRelayRaw(String from, List destinations, String rawMessage) { + try { + byte[] mimeBytes = tryBase64Decode(rawMessage); + var builder = new DefaultMessageBuilder(); + var message = builder.parseMessage(new ByteArrayInputStream(mimeBytes)); + + MailMessage mail = new MailMessage(); + + // From + if (message.getFrom() != null && !message.getFrom().isEmpty()) { + mail.setFrom(message.getFrom().get(0).getAddress()); + } else { + mail.setFrom(from); + } + + // 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. + 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)); + } + MailboxList ccList = message.getCc() != null ? message.getCc().flatten() : null; + if (ccList != null && !ccList.isEmpty()) { + mail.setCc(toMailboxAddresses(ccList)); + } + MailboxList bccList = message.getBcc() != null ? message.getBcc().flatten() : null; + if (bccList != null && !bccList.isEmpty()) { + mail.setBcc(toMailboxAddresses(bccList)); + } + } + + // Subject + mail.setSubject(message.getSubject() != null ? message.getSubject() : ""); + + // Body + extractBodyFromEntity(message, mail); + + 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); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOG.warnv(e, "SMTP raw relay interrupted for from={0}", from); + } catch (java.util.concurrent.TimeoutException e) { + LOG.warnv("SMTP raw relay timed out after {0}s for from={1}", RELAY_TIMEOUT_SECONDS, from); + } catch (Exception e) { + LOG.warnv(e, "SMTP raw relay failed for from={0}", from); + } + } + + private static void extractBodyFromEntity(Entity entity, MailMessage mail) { + 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) { + for (Entity part : multipart.getBodyParts()) { + extractBodyFromEntity(part, mail); + } + } + } + + private static String readTextBody(TextBody textBody) { + try { + Charset charset = StandardCharsets.UTF_8; + if (textBody.getMimeCharset() != null) { + try { + charset = Charset.forName(textBody.getMimeCharset()); + } catch (Exception ignored) {} + } + try (var is = textBody.getInputStream()) { + return new String(is.readAllBytes(), charset); + } + } catch (Exception e) { + return ""; + } + } + + private static List toMailboxAddresses(MailboxList list) { + List addresses = new ArrayList<>(); + for (Mailbox mailbox : list) { + addresses.add(mailbox.getAddress()); + } + return addresses; + } + + static byte[] tryBase64Decode(String data) { + try { + return Base64.getMimeDecoder().decode(data); + } catch (IllegalArgumentException e) { + return data.getBytes(StandardCharsets.UTF_8); + } + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 4f3cf92bb0..08d60a5a82 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -11,6 +11,7 @@ quarkus: native: additional-build-args: >- --initialize-at-run-time=org.apache.hc.client5.http.impl.auth.NTLMEngineImpl, + --initialize-at-run-time=io.vertx.ext.mail.impl.sasl.NTLMEngineImpl, --initialize-at-run-time=com.github.dockerjava.transport.NamedPipeSocket$Kernel32, --initialize-at-run-time=org.bouncycastle.jcajce.provider.drbg.DRBG$Default, --initialize-at-run-time=org.bouncycastle.jcajce.provider.drbg.DRBG$NonceAndIV, @@ -148,6 +149,11 @@ floci: enabled: true ses: enabled: true + # smtp-host: mailpit # SMTP server for email relay (empty = store only) + # smtp-port: 1025 + # smtp-user: "" + # smtp-pass: "" + # smtp-starttls: DISABLED # DISABLED, OPTIONAL, or REQUIRED opensearch: enabled: true mock: false diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java new file mode 100644 index 0000000000..a4c7c170cf --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java @@ -0,0 +1,98 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.ses.model.Identity; +import io.github.hectorvent.floci.services.ses.model.SentEmail; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class SesServiceSmtpTest { + + @Mock SmtpRelay smtpRelay; + + private SesService service; + private InMemoryStorage emailStore; + + @BeforeEach + void setUp() { + emailStore = new InMemoryStorage<>(); + service = new SesService( + new InMemoryStorage(), + emailStore, + new InMemoryStorage(), + smtpRelay); + } + + @Test + void sendEmail_callsRelayWithAllFields() { + 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"), + "Subject", "text body", "

html

", "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", "

html

"); + } + + @Test + void sendEmail_storesAndRelays() { + String messageId = service.sendEmail("from@example.com", + List.of("to@example.com"), null, null, null, + "Subject", "text", null, "us-east-1"); + + assertNotNull(messageId); + assertFalse(emailStore.scan(k -> true).isEmpty()); + verify(smtpRelay).relay(any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void sendRawEmail_callsRelayRaw() { + service.sendRawEmail("from@example.com", + List.of("to@example.com"), "raw MIME", "us-east-1"); + + verify(smtpRelay).relayRaw( + "from@example.com", + List.of("to@example.com"), + "raw MIME"); + } + + @Test + void sendRawEmail_storesAndRelays() { + String messageId = service.sendRawEmail("from@example.com", + List.of("to@example.com"), "raw", "us-east-1"); + + assertNotNull(messageId); + assertFalse(emailStore.scan(k -> true).isEmpty()); + verify(smtpRelay).relayRaw(any(), any(), any()); + } + + @Test + void sendEmail_relayReceivesCorrectFieldsWithNulls() { + service.sendEmail("from@example.com", + List.of("to@example.com"), + null, null, null, + "Subject", null, "

html only

", "us-east-1"); + + verify(smtpRelay).relay( + "from@example.com", + List.of("to@example.com"), + null, null, null, + "Subject", null, "

html only

"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SmtpRelayTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SmtpRelayTest.java new file mode 100644 index 0000000000..2692aa5150 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SmtpRelayTest.java @@ -0,0 +1,278 @@ +package io.github.hectorvent.floci.services.ses; + +import io.vertx.core.Future; +import io.vertx.ext.mail.MailClient; +import io.vertx.ext.mail.MailMessage; +import io.vertx.ext.mail.MailResult; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class SmtpRelayTest { + + @Mock MailClient mailClient; + + private SmtpRelay enabledRelay() { + when(mailClient.sendMail(any(MailMessage.class))) + .thenReturn(Future.succeededFuture(new MailResult())); + return new SmtpRelay(mailClient, true); + } + + @Test + void relay_whenDisabled_doesNotSend() { + 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); + + verify(mailClient, never()).sendMail(any(MailMessage.class)); + } + + @Test + 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", + "

html

"); + + ArgumentCaptor captor = ArgumentCaptor.forClass(MailMessage.class); + verify(mailClient).sendMail(captor.capture()); + + MailMessage sent = captor.getValue(); + assertEquals("from@example.com", sent.getFrom()); + assertEquals(List.of("to@example.com"), sent.getTo()); + assertEquals(List.of("cc@example.com"), sent.getCc()); + assertEquals(List.of("bcc@example.com"), sent.getBcc()); + assertEquals("Test Subject", sent.getSubject()); + assertEquals("plain text", sent.getText()); + assertEquals("

html

", sent.getHtml()); + assertEquals("reply@example.com", sent.getHeaders().get("Reply-To")); + } + + @Test + void relay_noReplyTo_omitsHeader() { + SmtpRelay relay = enabledRelay(); + + relay.relay("from@example.com", List.of("to@example.com"), + null, null, null, "Subject", "text", null); + + ArgumentCaptor captor = ArgumentCaptor.forClass(MailMessage.class); + verify(mailClient).sendMail(captor.capture()); + assertNull(captor.getValue().getHeaders()); + } + + @Test + void relay_textOnly_setsTextWithoutHtml() { + SmtpRelay relay = enabledRelay(); + + relay.relay("from@example.com", List.of("to@example.com"), + null, null, null, "Subject", "only text", null); + + ArgumentCaptor captor = ArgumentCaptor.forClass(MailMessage.class); + verify(mailClient).sendMail(captor.capture()); + assertEquals("only text", captor.getValue().getText()); + assertNull(captor.getValue().getHtml()); + } + + @Test + void relay_htmlOnly_setsHtmlWithoutText() { + SmtpRelay relay = enabledRelay(); + + relay.relay("from@example.com", List.of("to@example.com"), + null, null, null, "Subject", null, "html"); + + ArgumentCaptor captor = ArgumentCaptor.forClass(MailMessage.class); + verify(mailClient).sendMail(captor.capture()); + assertNull(captor.getValue().getText()); + assertEquals("html", captor.getValue().getHtml()); + } + + @Test + void relay_mailClientThrows_doesNotPropagate() { + SmtpRelay relay = new SmtpRelay(mailClient, true); + 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)); + } + + // ── Raw relay ── + + @Test + void relayRaw_whenDisabled_doesNotSend() { + SmtpRelay relay = new SmtpRelay(mailClient, false); + + relay.relayRaw("from@example.com", List.of("to@example.com"), "raw"); + + verify(mailClient, never()).sendMail(any(MailMessage.class)); + } + + @Test + void relayRaw_parsesHeadersAndBody() { + SmtpRelay relay = enabledRelay(); + + String rawMime = "From: sender@example.com\r\n" + + "To: to@example.com\r\n" + + "Subject: Raw Test\r\n" + + "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); + + ArgumentCaptor captor = ArgumentCaptor.forClass(MailMessage.class); + verify(mailClient).sendMail(captor.capture()); + + MailMessage sent = captor.getValue(); + assertEquals("sender@example.com", sent.getFrom()); + assertEquals(List.of("dest@example.com"), sent.getTo()); + assertEquals("Raw Test", sent.getSubject()); + assertEquals("Raw body content", sent.getText()); + } + + @Test + void relayRaw_base64Encoded_decodesFirst() { + SmtpRelay relay = enabledRelay(); + + 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); + + ArgumentCaptor captor = ArgumentCaptor.forClass(MailMessage.class); + verify(mailClient).sendMail(captor.capture()); + assertEquals("B64", captor.getValue().getSubject()); + assertEquals("Decoded body", captor.getValue().getText()); + } + + @Test + void relayRaw_htmlContentType_setsHtml() { + SmtpRelay relay = enabledRelay(); + + 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

Hello

"; + relay.relayRaw("from@example.com", List.of("to@example.com"), rawMime); + + ArgumentCaptor captor = ArgumentCaptor.forClass(MailMessage.class); + verify(mailClient).sendMail(captor.capture()); + assertEquals("

Hello

", captor.getValue().getHtml()); + assertNull(captor.getValue().getText()); + } + + @Test + void relayRaw_destinationsEmpty_extractsBccFromHeaders() { + SmtpRelay relay = enabledRelay(); + + String rawMime = "From: s@example.com\r\n" + + "To: t@example.com\r\n" + + "Cc: c@example.com\r\n" + + "Bcc: b@example.com\r\n" + + "Subject: BccHeader\r\n" + + "Content-Type: text/plain; charset=UTF-8\r\n" + + "\r\n" + + "body"; + relay.relayRaw("envelope@example.com", null, rawMime); + + ArgumentCaptor captor = ArgumentCaptor.forClass(MailMessage.class); + verify(mailClient).sendMail(captor.capture()); + MailMessage sent = captor.getValue(); + assertEquals(List.of("t@example.com"), sent.getTo()); + assertEquals(List.of("c@example.com"), sent.getCc()); + assertEquals(List.of("b@example.com"), sent.getBcc()); + } + + @Test + void relayRaw_fallsBackToEnvelopeAddresses() { + SmtpRelay relay = enabledRelay(); + + String rawMime = "Subject: NoAddr\r\n\r\nBody"; + relay.relayRaw("envelope@example.com", List.of("dest@example.com"), rawMime); + + ArgumentCaptor captor = ArgumentCaptor.forClass(MailMessage.class); + verify(mailClient).sendMail(captor.capture()); + assertEquals("envelope@example.com", captor.getValue().getFrom()); + assertEquals(List.of("dest@example.com"), captor.getValue().getTo()); + } + + @Test + void relayRaw_nestedMultipart_extractsTextAndHtml() { + SmtpRelay relay = enabledRelay(); + + String rawMime = "From: s@example.com\r\n" + + "To: t@example.com\r\n" + + "Subject: Nested\r\n" + + "Content-Type: multipart/mixed; boundary=\"outer\"\r\n" + + "\r\n" + + "--outer\r\n" + + "Content-Type: multipart/alternative; boundary=\"inner\"\r\n" + + "\r\n" + + "--inner\r\n" + + "Content-Type: text/plain; charset=UTF-8\r\n" + + "\r\n" + + "plain text\r\n" + + "--inner\r\n" + + "Content-Type: text/html; charset=UTF-8\r\n" + + "\r\n" + + "

html

\r\n" + + "--inner--\r\n" + + "--outer--"; + relay.relayRaw("from@example.com", List.of("to@example.com"), rawMime); + + ArgumentCaptor captor = ArgumentCaptor.forClass(MailMessage.class); + verify(mailClient).sendMail(captor.capture()); + assertEquals("plain text", captor.getValue().getText().trim()); + assertEquals("

html

", captor.getValue().getHtml().trim()); + } + + @Test + void relayRaw_multipartMixedWithTextAttachment_preservesBody() { + 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 that must not clobber body\r\n" + + "--outer--"; + relay.relayRaw("from@example.com", List.of("to@example.com"), rawMime); + + ArgumentCaptor captor = ArgumentCaptor.forClass(MailMessage.class); + verify(mailClient).sendMail(captor.capture()); + assertEquals("real body", captor.getValue().getText().trim()); + } + + @Test + void relayRaw_mailClientThrows_doesNotPropagate() { + SmtpRelay relay = new SmtpRelay(mailClient, true); + 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")); + } +}