Light, fluffy, and always free - The AWS Local Emulator alternative
feat(ses): SMTP relay for SendEmail and SendRawEmail (#534)
Kenshin Okinakac69580764ebf
diff --git a/docs/configuration/application-yml.md b/docs/configuration/application-yml.mdindex 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 REQUIREDopensearch: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.mdindex 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=<message-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=<message-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.xmlindex 993900fe9a..e24ab5d618 100644--- a/pom.xml+++ b/pom.xml@@ -48,6 +48,17 @@<groupId>io.quarkus</groupId><artifactId>quarkus-config-yaml</artifactId></dependency>+ <!-- Vert.x mail client for SES SMTP relay -->+ <dependency>+ <groupId>io.vertx</groupId>+ <artifactId>vertx-mail-client</artifactId>+ </dependency>+ <!-- MIME parsing for raw email relay -->+ <dependency>+ <groupId>org.apache.james</groupId>+ <artifactId>apache-mime4j-dom</artifactId>+ <version>0.8.11</version>+ </dependency><!-- Jackson for JSON storage serialization --><dependency>diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 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<String> smtpHost();++ /** SMTP server port. */+ @WithDefault("25")+ int smtpPort();++ /** SMTP authentication username. Empty = no authentication. */+ Optional<String> smtpUser();++ /** SMTP authentication password. */+ Optional<String> 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.javaindex 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<String, Identity> identityStore;private final StorageBackend<String, SentEmail> emailStore;private final StorageBackend<String, Boolean> 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<Map<String, Identity>>() {});this.emailStore = storageFactory.create("ses", "ses-emails.json",new TypeReference<Map<String, SentEmail>>() {});this.accountSettingsStore = storageFactory.create("ses", "ses-account-settings.json",new TypeReference<Map<String, Boolean>>() {});+ this.smtpRelay = smtpRelay;}SesService(StorageBackend<String, Identity> identityStore,StorageBackend<String, SentEmail> emailStore,- StorageBackend<String, Boolean> accountSettingsStore) {+ StorageBackend<String, Boolean> 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.javanew file mode 100644index 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.+ *+ * <p>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<Runnable> 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<String> toAddresses, List<String> ccAddresses,+ List<String> bccAddresses, List<String> 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<String> toAddresses, List<String> ccAddresses,+ List<String> bccAddresses, List<String> 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<String> 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<String> 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<String> toMailboxAddresses(MailboxList list) {+ List<String> 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.ymlindex 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: trueses: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 REQUIREDopensearch:enabled: truemock: falsediff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.javanew file mode 100644index 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<String, SentEmail> emailStore;++ @BeforeEach+ void setUp() {+ emailStore = new InMemoryStorage<>();+ service = new SesService(+ new InMemoryStorage<String, Identity>(),+ emailStore,+ new InMemoryStorage<String, Boolean>(),+ smtpRelay);+ }++ @Test+ void sendEmail_callsRelayWithAllFields() {+ service.sendEmail("[email protected]",+ List.of("[email protected]"),+ List.of("[email protected]"),+ List.of("[email protected]"),+ List.of("[email protected]"),+ "Subject", "text body", "<p>html</p>", "us-east-1");++ verify(smtpRelay).relay(+ "[email protected]",+ List.of("[email protected]"),+ List.of("[email protected]"),+ List.of("[email protected]"),+ List.of("[email protected]"),+ "Subject", "text body", "<p>html</p>");+ }++ @Test+ void sendEmail_storesAndRelays() {+ String messageId = service.sendEmail("[email protected]",+ List.of("[email protected]"), 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("[email protected]",+ List.of("[email protected]"), "raw MIME", "us-east-1");++ verify(smtpRelay).relayRaw(+ "[email protected]",+ List.of("[email protected]"),+ "raw MIME");+ }++ @Test+ void sendRawEmail_storesAndRelays() {+ String messageId = service.sendRawEmail("[email protected]",+ List.of("[email protected]"), "raw", "us-east-1");++ assertNotNull(messageId);+ assertFalse(emailStore.scan(k -> true).isEmpty());+ verify(smtpRelay).relayRaw(any(), any(), any());+ }++ @Test+ void sendEmail_relayReceivesCorrectFieldsWithNulls() {+ service.sendEmail("[email protected]",+ List.of("[email protected]"),+ null, null, null,+ "Subject", null, "<p>html only</p>", "us-east-1");++ verify(smtpRelay).relay(+ "[email protected]",+ List.of("[email protected]"),+ null, null, null,+ "Subject", null, "<p>html only</p>");+ }+}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.javanew file mode 100644index 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("[email protected]", List.of("[email protected]"),+ null, null, null, "Subject", "text", null);++ verify(mailClient, never()).sendMail(any(MailMessage.class));+ }++ @Test+ void relay_whenEnabled_sendsMail() {+ SmtpRelay relay = enabledRelay();++ relay.relay("[email protected]",+ List.of("[email protected]"),+ List.of("[email protected]"),+ List.of("[email protected]"),+ List.of("[email protected]"),+ "Test Subject",+ "plain text",+ "<p>html</p>");++ ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);+ verify(mailClient).sendMail(captor.capture());++ MailMessage sent = captor.getValue();+ assertEquals("[email protected]", sent.getFrom());+ assertEquals(List.of("[email protected]"), sent.getTo());+ assertEquals(List.of("[email protected]"), sent.getCc());+ assertEquals(List.of("[email protected]"), sent.getBcc());+ assertEquals("Test Subject", sent.getSubject());+ assertEquals("plain text", sent.getText());+ assertEquals("<p>html</p>", sent.getHtml());+ assertEquals("[email protected]", sent.getHeaders().get("Reply-To"));+ }++ @Test+ void relay_noReplyTo_omitsHeader() {+ SmtpRelay relay = enabledRelay();++ relay.relay("[email protected]", List.of("[email protected]"),+ null, null, null, "Subject", "text", null);++ ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);+ verify(mailClient).sendMail(captor.capture());+ assertNull(captor.getValue().getHeaders());+ }++ @Test+ void relay_textOnly_setsTextWithoutHtml() {+ SmtpRelay relay = enabledRelay();++ relay.relay("[email protected]", List.of("[email protected]"),+ null, null, null, "Subject", "only text", null);++ ArgumentCaptor<MailMessage> 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("[email protected]", List.of("[email protected]"),+ null, null, null, "Subject", null, "<b>html</b>");++ ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);+ verify(mailClient).sendMail(captor.capture());+ assertNull(captor.getValue().getText());+ assertEquals("<b>html</b>", 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("[email protected]",+ List.of("[email protected]"), null, null, null, "Subject", "text", null));+ }++ // ── Raw relay ──++ @Test+ void relayRaw_whenDisabled_doesNotSend() {+ SmtpRelay relay = new SmtpRelay(mailClient, false);++ relay.relayRaw("[email protected]", List.of("[email protected]"), "raw");++ verify(mailClient, never()).sendMail(any(MailMessage.class));+ }++ @Test+ void relayRaw_parsesHeadersAndBody() {+ SmtpRelay relay = enabledRelay();++ String rawMime = "From: [email protected]\r\n"+ + "To: [email protected]\r\n"+ + "Subject: Raw Test\r\n"+ + "Content-Type: text/plain; charset=UTF-8\r\n"+ + "\r\n"+ + "Raw body content";+ relay.relayRaw("[email protected]", List.of("[email protected]"), rawMime);++ ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);+ verify(mailClient).sendMail(captor.capture());++ MailMessage sent = captor.getValue();+ assertEquals("[email protected]", sent.getFrom());+ assertEquals(List.of("[email protected]"), sent.getTo());+ assertEquals("Raw Test", sent.getSubject());+ assertEquals("Raw body content", sent.getText());+ }++ @Test+ void relayRaw_base64Encoded_decodesFirst() {+ SmtpRelay relay = enabledRelay();++ String rawMime = "From: [email protected]\r\nTo: [email protected]\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("[email protected]", List.of("[email protected]"), encoded);++ ArgumentCaptor<MailMessage> 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: [email protected]\r\nTo: [email protected]\r\nSubject: HTML\r\n"+ + "Content-Type: text/html; charset=UTF-8\r\n\r\n<h1>Hello</h1>";+ relay.relayRaw("[email protected]", List.of("[email protected]"), rawMime);++ ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);+ verify(mailClient).sendMail(captor.capture());+ assertEquals("<h1>Hello</h1>", captor.getValue().getHtml());+ assertNull(captor.getValue().getText());+ }++ @Test+ void relayRaw_destinationsEmpty_extractsBccFromHeaders() {+ SmtpRelay relay = enabledRelay();++ String rawMime = "From: [email protected]\r\n"+ + "To: [email protected]\r\n"+ + "Cc: [email protected]\r\n"+ + "Bcc: [email protected]\r\n"+ + "Subject: BccHeader\r\n"+ + "Content-Type: text/plain; charset=UTF-8\r\n"+ + "\r\n"+ + "body";+ relay.relayRaw("[email protected]", null, rawMime);++ ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);+ verify(mailClient).sendMail(captor.capture());+ MailMessage sent = captor.getValue();+ assertEquals(List.of("[email protected]"), sent.getTo());+ assertEquals(List.of("[email protected]"), sent.getCc());+ assertEquals(List.of("[email protected]"), sent.getBcc());+ }++ @Test+ void relayRaw_fallsBackToEnvelopeAddresses() {+ SmtpRelay relay = enabledRelay();++ String rawMime = "Subject: NoAddr\r\n\r\nBody";+ relay.relayRaw("[email protected]", List.of("[email protected]"), rawMime);++ ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);+ verify(mailClient).sendMail(captor.capture());+ assertEquals("[email protected]", captor.getValue().getFrom());+ assertEquals(List.of("[email protected]"), captor.getValue().getTo());+ }++ @Test+ void relayRaw_nestedMultipart_extractsTextAndHtml() {+ SmtpRelay relay = enabledRelay();++ String rawMime = "From: [email protected]\r\n"+ + "To: [email protected]\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"+ + "<p>html</p>\r\n"+ + "--inner--\r\n"+ + "--outer--";+ relay.relayRaw("[email protected]", List.of("[email protected]"), rawMime);++ ArgumentCaptor<MailMessage> captor = ArgumentCaptor.forClass(MailMessage.class);+ verify(mailClient).sendMail(captor.capture());+ assertEquals("plain text", captor.getValue().getText().trim());+ assertEquals("<p>html</p>", captor.getValue().getHtml().trim());+ }++ @Test+ void relayRaw_multipartMixedWithTextAttachment_preservesBody() {+ SmtpRelay relay = enabledRelay();++ String rawMime = "From: [email protected]\r\n"+ + "To: [email protected]\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("[email protected]", List.of("[email protected]"), rawMime);++ ArgumentCaptor<MailMessage> 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("[email protected]",+ List.of("[email protected]"), "Subject: X\r\n\r\nBody"));+ }+}