From 9bf23d5513ddeeca83b9185baea34b5fb2dbeaa9 Mon Sep 17 00:00:00 2001 From: David Hunter Date: Thu, 26 Mar 2026 10:38:23 -0600 Subject: [PATCH] feat: add SES (Simple Email Service) emulation (#14) Thanks again, @daphid4! This is a great addition to Floci. Your continued support really makes a difference. Hope to see you around soon! --- * feat: add SES (Simple Email Service) emulation Implements SES v1 Query protocol with the following actions: - VerifyEmailIdentity, VerifyEmailAddress, VerifyDomainIdentity - DeleteIdentity, ListIdentities, GetIdentityVerificationAttributes - SendEmail, SendRawEmail - GetSendQuota, GetSendStatistics, GetAccountSendingEnabled - ListVerifiedEmailAddresses, DeleteVerifiedEmailAddress - SetIdentityNotificationTopic, GetIdentityNotificationAttributes - GetIdentityDkimAttributes Identities are auto-verified in the emulator for local development. Sent emails are stored in-memory and accessible via statistics APIs. All 20 integration tests passing, full suite (537 tests) green. --- pom.xml | 2 +- .../floci/config/EmulatorConfig.java | 6 + .../floci/core/common/AwsNamespaces.java | 1 + .../floci/core/common/AwsQueryController.java | 19 +- .../floci/core/common/ServiceRegistry.java | 2 + .../services/ses/SesInspectionController.java | 92 +++++ .../floci/services/ses/SesQueryHandler.java | 262 +++++++++++++ .../floci/services/ses/SesService.java | 183 +++++++++ .../floci/services/ses/model/Identity.java | 74 ++++ .../floci/services/ses/model/SentEmail.java | 76 ++++ src/main/resources/application.yml | 2 + .../services/ses/SesIntegrationTest.java | 350 ++++++++++++++++++ 12 files changed, 1067 insertions(+), 2 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/ses/SesInspectionController.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/ses/SesService.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/ses/model/Identity.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/ses/model/SentEmail.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ses/SesIntegrationTest.java diff --git a/pom.xml b/pom.xml index 792765b441..c7289355a1 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ jar Floci - Fast, free, open-source local AWS emulator supporting SSM, SQS, SNS, S3, DynamoDB, Lambda, API Gateway, Cognito, KMS, Kinesis, Secrets Manager, CloudFormation, Step Functions, IAM, STS, ElastiCache, RDS, EventBridge, and CloudWatch + Fast, free, open-source local AWS emulator supporting SSM, SQS, SNS, SES, S3, DynamoDB, Lambda, API Gateway, Cognito, KMS, Kinesis, Secrets Manager, CloudFormation, Step Functions, IAM, STS, ElastiCache, RDS, EventBridge, and CloudWatch 25 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 33125417b0..88c27d1b4b 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -182,6 +182,7 @@ public interface EmulatorConfig { StepFunctionsServiceConfig stepfunctions(); CloudFormationServiceConfig cloudformation(); AcmServiceConfig acm(); + SesServiceConfig ses(); } interface SsmServiceConfig { @@ -336,6 +337,11 @@ public interface EmulatorConfig { int validationWaitSeconds(); } + interface SesServiceConfig { + @WithDefault("true") + boolean enabled(); + } + interface LambdaServiceConfig { @WithDefault("true") boolean enabled(); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsNamespaces.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsNamespaces.java index e4f8e74da3..aa0e03028c 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsNamespaces.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsNamespaces.java @@ -14,6 +14,7 @@ public final class AwsNamespaces { public static final String EC = "http://elasticache.amazonaws.com/doc/2015-02-02/"; public static final String CW = "http://monitoring.amazonaws.com/doc/2010-08-01/"; public static final String S3 = "http://s3.amazonaws.com/doc/2006-03-01/"; + public static final String SES = "http://ses.amazonaws.com/doc/2010-12-01/"; private AwsNamespaces() {} } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java index aa2554bfed..e0cfc8f56c 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java @@ -7,6 +7,7 @@ import io.github.hectorvent.floci.services.iam.IamQueryHandler; import io.github.hectorvent.floci.services.iam.StsQueryHandler; import io.github.hectorvent.floci.services.rds.RdsQueryHandler; import io.github.hectorvent.floci.services.sns.SnsQueryHandler; +import io.github.hectorvent.floci.services.ses.SesQueryHandler; import io.github.hectorvent.floci.services.sqs.SqsQueryHandler; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; @@ -104,6 +105,7 @@ public class AwsQueryController { private final RdsQueryHandler rdsQueryHandler; private final SqsQueryHandler sqsQueryHandler; private final SnsQueryHandler snsQueryHandler; + private final SesQueryHandler sesQueryHandler; private final IamQueryHandler iamQueryHandler; private final StsQueryHandler stsQueryHandler; private final CloudWatchMetricsQueryHandler cloudWatchMetricsQueryHandler; @@ -114,6 +116,7 @@ public class AwsQueryController { ElastiCacheQueryHandler elastiCacheQueryHandler, RdsQueryHandler rdsQueryHandler, SqsQueryHandler sqsQueryHandler, SnsQueryHandler snsQueryHandler, + SesQueryHandler sesQueryHandler, IamQueryHandler iamQueryHandler, StsQueryHandler stsQueryHandler, CloudWatchMetricsQueryHandler cloudWatchMetricsQueryHandler, RegionResolver regionResolver) { @@ -122,6 +125,7 @@ public class AwsQueryController { this.rdsQueryHandler = rdsQueryHandler; this.sqsQueryHandler = sqsQueryHandler; this.snsQueryHandler = snsQueryHandler; + this.sesQueryHandler = sesQueryHandler; this.iamQueryHandler = iamQueryHandler; this.stsQueryHandler = stsQueryHandler; this.cloudWatchMetricsQueryHandler = cloudWatchMetricsQueryHandler; @@ -153,6 +157,7 @@ public class AwsQueryController { case "sts" -> stsQueryHandler.handle(action, formParams); case "elasticache" -> elastiCacheQueryHandler.handle(action, formParams); case "rds" -> rdsQueryHandler.handle(action, formParams); + case "email" -> sesQueryHandler.handle(action, formParams, region); case "monitoring" -> cloudWatchMetricsQueryHandler.handle(action, formParams, region); case "cloudformation" -> cloudFormationQueryHandler.handle(action, formParams, region); default -> xmlErrorResponse("UnknownService", @@ -191,7 +196,16 @@ public class AwsQueryController { "SetStackPolicy", "GetStackPolicy", "ListStackSets", "DescribeStackSet", "CreateStackSet" ); - private static final Set QUERY_PROTOCOL_SERVICES = Set.of("sqs", "sns", "iam", "sts", "elasticache", "rds", "monitoring", "cloudformation"); + private static final Set SES_ACTIONS = Set.of( + "VerifyEmailIdentity", "VerifyEmailAddress", "VerifyDomainIdentity", + "DeleteIdentity", "ListIdentities", "GetIdentityVerificationAttributes", + "SendEmail", "SendRawEmail", "GetSendQuota", "GetSendStatistics", + "GetAccountSendingEnabled", "ListVerifiedEmailAddresses", "DeleteVerifiedEmailAddress", + "SetIdentityNotificationTopic", "GetIdentityNotificationAttributes", + "GetIdentityDkimAttributes" + ); + + private static final Set QUERY_PROTOCOL_SERVICES = Set.of("sqs", "sns", "iam", "sts", "elasticache", "rds", "monitoring", "cloudformation", "email"); private String resolveService(String authorization, String action) { if (authorization != null && !authorization.isEmpty()) { @@ -228,6 +242,9 @@ public class AwsQueryController { if (CLOUDFORMATION_ACTIONS.contains(action)) { return "cloudformation"; } + if (SES_ACTIONS.contains(action)) { + return "email"; + } // SQS actions are numerous and not enumerated — fall back to sqs only for // requests that arrived without an Authorization header (raw/test clients) return "sqs"; diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ServiceRegistry.java b/src/main/java/io/github/hectorvent/floci/core/common/ServiceRegistry.java index 178a5d1370..9fd075f94a 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ServiceRegistry.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ServiceRegistry.java @@ -46,6 +46,7 @@ public class ServiceRegistry { case "states" -> config.services().stepfunctions().enabled(); case "cloudformation" -> config.services().cloudformation().enabled(); case "acm" -> config.services().acm().enabled(); + case "email" -> config.services().ses().enabled(); default -> true; }; } @@ -73,6 +74,7 @@ public class ServiceRegistry { if (config.services().stepfunctions().enabled()) enabled.add("states"); if (config.services().cloudformation().enabled()) enabled.add("cloudformation"); if (config.services().acm().enabled()) enabled.add("acm"); + if (config.services().ses().enabled()) enabled.add("email"); return enabled; } diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesInspectionController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesInspectionController.java new file mode 100644 index 0000000000..aac1219e5b --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesInspectionController.java @@ -0,0 +1,92 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.ses.model.SentEmail; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import jakarta.inject.Inject; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +import java.util.List; + +/** + * LocalStack-compatible REST endpoint for inspecting sent SES emails. + * Provides GET /_aws/ses and DELETE /_aws/ses for test helpers. + */ +@Path("/_aws/ses") +@Produces(MediaType.APPLICATION_JSON) +public class SesInspectionController { + + private final SesService sesService; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public SesInspectionController(SesService sesService, RegionResolver regionResolver, + ObjectMapper objectMapper) { + this.sesService = sesService; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + @GET + public Response getEmails(@QueryParam("id") String messageId) { + String region = regionResolver.getDefaultRegion(); + List emails = sesService.getEmails(region); + + ArrayNode messages = objectMapper.createArrayNode(); + for (SentEmail email : emails) { + if (messageId != null && !messageId.equals(email.getMessageId())) { + continue; + } + ObjectNode node = objectMapper.createObjectNode(); + node.put("Id", email.getMessageId()); + node.put("Region", region); + node.put("Source", email.getSource()); + + ObjectNode destination = node.putObject("Destination"); + if (email.getToAddresses() != null) { + ArrayNode toArr = destination.putArray("ToAddresses"); + email.getToAddresses().forEach(toArr::add); + } + if (email.getCcAddresses() != null) { + ArrayNode ccArr = destination.putArray("CcAddresses"); + email.getCcAddresses().forEach(ccArr::add); + } + if (email.getBccAddresses() != null) { + ArrayNode bccArr = destination.putArray("BccAddresses"); + email.getBccAddresses().forEach(bccArr::add); + } + + node.put("Subject", email.getSubject()); + + ObjectNode body = node.putObject("Body"); + body.put("text_part", email.getBody() != null ? email.getBody() : ""); + body.put("html_part", email.getBody() != null ? email.getBody() : ""); + + if (email.getSentAt() != null) { + node.put("Timestamp", email.getSentAt().toString()); + } + + messages.add(node); + } + + ObjectNode result = objectMapper.createObjectNode(); + result.set("messages", messages); + return Response.ok(result).build(); + } + + @DELETE + public Response clearEmails() { + String region = regionResolver.getDefaultRegion(); + sesService.clearEmails(region); + return Response.ok().build(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java new file mode 100644 index 0000000000..898e03c253 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java @@ -0,0 +1,262 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.AwsNamespaces; +import io.github.hectorvent.floci.core.common.AwsQueryResponse; +import io.github.hectorvent.floci.core.common.XmlBuilder; +import io.github.hectorvent.floci.services.ses.model.Identity; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; +import org.jboss.logging.Logger; + +import java.util.ArrayList; +import java.util.List; + +/** + * Query-protocol handler for SES actions. + * Receives pre-dispatched calls from {@link io.github.hectorvent.floci.core.common.AwsQueryController}. + */ +@ApplicationScoped +public class SesQueryHandler { + + private static final Logger LOG = Logger.getLogger(SesQueryHandler.class); + + private final SesService sesService; + + @Inject + public SesQueryHandler(SesService sesService) { + this.sesService = sesService; + } + + public Response handle(String action, MultivaluedMap params, String region) { + LOG.debugv("SES action: {0}", action); + + try { + return switch (action) { + case "VerifyEmailIdentity" -> handleVerifyEmailIdentity(params, region); + case "VerifyEmailAddress" -> handleVerifyEmailAddress(params, region); + case "VerifyDomainIdentity" -> handleVerifyDomainIdentity(params, region); + case "DeleteIdentity" -> handleDeleteIdentity(params, region); + case "ListIdentities" -> handleListIdentities(params, region); + case "GetIdentityVerificationAttributes" -> handleGetIdentityVerificationAttributes(params, region); + case "SendEmail" -> handleSendEmail(params, region); + case "SendRawEmail" -> handleSendRawEmail(params, region); + case "GetSendQuota" -> handleGetSendQuota(region); + case "GetSendStatistics" -> handleGetSendStatistics(region); + case "GetAccountSendingEnabled" -> handleGetAccountSendingEnabled(); + case "ListVerifiedEmailAddresses" -> handleListVerifiedEmailAddresses(region); + case "DeleteVerifiedEmailAddress" -> handleDeleteVerifiedEmailAddress(params, region); + case "SetIdentityNotificationTopic" -> handleSetIdentityNotificationTopic(params, region); + case "GetIdentityNotificationAttributes" -> handleGetIdentityNotificationAttributes(params, region); + case "GetIdentityDkimAttributes" -> handleGetIdentityDkimAttributes(params, region); + default -> AwsQueryResponse.error("UnsupportedOperation", + "Operation " + action + " is not supported by SES.", AwsNamespaces.SES, 400); + }; + } catch (AwsException e) { + return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.SES, e.getHttpStatus()); + } + } + + private Response handleVerifyEmailIdentity(MultivaluedMap params, String region) { + String emailAddress = getParam(params, "EmailAddress"); + sesService.verifyEmailIdentity(emailAddress, region); + return Response.ok(AwsQueryResponse.envelopeNoResult("VerifyEmailIdentity", AwsNamespaces.SES)).build(); + } + + private Response handleVerifyEmailAddress(MultivaluedMap params, String region) { + String emailAddress = getParam(params, "EmailAddress"); + sesService.verifyEmailIdentity(emailAddress, region); + return Response.ok(AwsQueryResponse.envelopeNoResult("VerifyEmailAddress", AwsNamespaces.SES)).build(); + } + + private Response handleVerifyDomainIdentity(MultivaluedMap params, String region) { + String domain = getParam(params, "Domain"); + Identity identity = sesService.verifyDomainIdentity(domain, region); + String result = new XmlBuilder().elem("VerificationToken", identity.getVerificationToken()).build(); + return Response.ok(AwsQueryResponse.envelope("VerifyDomainIdentity", AwsNamespaces.SES, result)).build(); + } + + private Response handleDeleteIdentity(MultivaluedMap params, String region) { + String identityValue = getParam(params, "Identity"); + sesService.deleteIdentity(identityValue, region); + return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteIdentity", AwsNamespaces.SES)).build(); + } + + private Response handleListIdentities(MultivaluedMap params, String region) { + String identityType = getParam(params, "IdentityType"); + List identities = sesService.listIdentities(identityType, region); + + var xml = new XmlBuilder().start("Identities"); + for (Identity id : identities) { + xml.elem("member", id.getIdentity()); + } + xml.end("Identities"); + return Response.ok(AwsQueryResponse.envelope("ListIdentities", AwsNamespaces.SES, xml.build())).build(); + } + + private Response handleGetIdentityVerificationAttributes(MultivaluedMap params, String region) { + List identities = extractMembers(params, "Identities"); + + var xml = new XmlBuilder().start("VerificationAttributes"); + for (String identityValue : identities) { + Identity identity = sesService.getIdentityVerificationAttributes(identityValue, region); + xml.start("entry"); + xml.elem("key", identityValue); + xml.start("value"); + if (identity != null) { + xml.elem("VerificationStatus", identity.getVerificationStatus()); + if (identity.getVerificationToken() != null) { + xml.elem("VerificationToken", identity.getVerificationToken()); + } + } else { + xml.elem("VerificationStatus", "NotStarted"); + } + xml.end("value"); + xml.end("entry"); + } + xml.end("VerificationAttributes"); + return Response.ok(AwsQueryResponse.envelope("GetIdentityVerificationAttributes", AwsNamespaces.SES, xml.build())).build(); + } + + private Response handleSendEmail(MultivaluedMap params, String region) { + String source = getParam(params, "Source"); + List toAddresses = extractMembers(params, "Destination.ToAddresses"); + List ccAddresses = extractMembers(params, "Destination.CcAddresses"); + List bccAddresses = extractMembers(params, "Destination.BccAddresses"); + String subject = getParam(params, "Message.Subject.Data"); + String bodyText = getParam(params, "Message.Body.Text.Data"); + String bodyHtml = getParam(params, "Message.Body.Html.Data"); + + String messageId = sesService.sendEmail(source, toAddresses, ccAddresses, bccAddresses, + subject, bodyText, bodyHtml, region); + + String result = new XmlBuilder().elem("MessageId", messageId).build(); + return Response.ok(AwsQueryResponse.envelope("SendEmail", AwsNamespaces.SES, result)).build(); + } + + private Response handleSendRawEmail(MultivaluedMap params, String region) { + String source = getParam(params, "Source"); + List destinations = extractMembers(params, "Destinations"); + String rawMessage = getParam(params, "RawMessage.Data"); + + String messageId = sesService.sendRawEmail(source, destinations, rawMessage, region); + + String result = new XmlBuilder().elem("MessageId", messageId).build(); + return Response.ok(AwsQueryResponse.envelope("SendRawEmail", AwsNamespaces.SES, result)).build(); + } + + private Response handleGetSendQuota(String region) { + var xml = new XmlBuilder() + .elem("Max24HourSend", "200.0") + .elem("MaxSendRate", "1.0") + .elem("SentLast24Hours", String.valueOf((double) sesService.getSentEmailCount(region))); + return Response.ok(AwsQueryResponse.envelope("GetSendQuota", AwsNamespaces.SES, xml.build())).build(); + } + + private Response handleGetSendStatistics(String region) { + long sentCount = sesService.getSentEmailCount(region); + var xml = new XmlBuilder().start("SendDataPoints"); + if (sentCount > 0) { + xml.start("member") + .elem("DeliveryAttempts", String.valueOf(sentCount)) + .elem("Bounces", "0") + .elem("Complaints", "0") + .elem("Rejects", "0") + .elem("Timestamp", java.time.Instant.now().toString()) + .end("member"); + } + xml.end("SendDataPoints"); + return Response.ok(AwsQueryResponse.envelope("GetSendStatistics", AwsNamespaces.SES, xml.build())).build(); + } + + private Response handleGetAccountSendingEnabled() { + String result = new XmlBuilder().elem("Enabled", "true").build(); + return Response.ok(AwsQueryResponse.envelope("GetAccountSendingEnabled", AwsNamespaces.SES, result)).build(); + } + + private Response handleListVerifiedEmailAddresses(String region) { + List emails = sesService.getVerifiedEmailAddresses(region); + var xml = new XmlBuilder().start("VerifiedEmailAddresses"); + for (String email : emails) { + xml.elem("member", email); + } + xml.end("VerifiedEmailAddresses"); + return Response.ok(AwsQueryResponse.envelope("ListVerifiedEmailAddresses", AwsNamespaces.SES, xml.build())).build(); + } + + private Response handleDeleteVerifiedEmailAddress(MultivaluedMap params, String region) { + String emailAddress = getParam(params, "EmailAddress"); + sesService.deleteIdentity(emailAddress, region); + return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteVerifiedEmailAddress", AwsNamespaces.SES)).build(); + } + + private Response handleSetIdentityNotificationTopic(MultivaluedMap params, String region) { + String identityValue = getParam(params, "Identity"); + String notificationType = getParam(params, "NotificationType"); + String snsTopic = getParam(params, "SnsTopic"); + sesService.setIdentityNotificationTopic(identityValue, notificationType, snsTopic, region); + return Response.ok(AwsQueryResponse.envelopeNoResult("SetIdentityNotificationTopic", AwsNamespaces.SES)).build(); + } + + private Response handleGetIdentityNotificationAttributes(MultivaluedMap params, String region) { + List identities = extractMembers(params, "Identities"); + + var xml = new XmlBuilder().start("NotificationAttributes"); + for (String identityValue : identities) { + Identity identity = sesService.getIdentityNotificationAttributes(identityValue, region); + xml.start("entry"); + xml.elem("key", identityValue); + xml.start("value"); + if (identity != null) { + xml.elem("BounceTopic", identity.getNotificationAttributes().getOrDefault("BounceTopic", "")); + xml.elem("ComplaintTopic", identity.getNotificationAttributes().getOrDefault("ComplaintTopic", "")); + xml.elem("DeliveryTopic", identity.getNotificationAttributes().getOrDefault("DeliveryTopic", "")); + xml.elem("ForwardingEnabled", "true"); + xml.elem("HeadersInBounceNotificationsEnabled", "false"); + xml.elem("HeadersInComplaintNotificationsEnabled", "false"); + xml.elem("HeadersInDeliveryNotificationsEnabled", "false"); + } + xml.end("value"); + xml.end("entry"); + } + xml.end("NotificationAttributes"); + return Response.ok(AwsQueryResponse.envelope("GetIdentityNotificationAttributes", AwsNamespaces.SES, xml.build())).build(); + } + + private Response handleGetIdentityDkimAttributes(MultivaluedMap params, String region) { + List identities = extractMembers(params, "Identities"); + + var xml = new XmlBuilder().start("DkimAttributes"); + for (String identityValue : identities) { + Identity identity = sesService.getIdentityVerificationAttributes(identityValue, region); + xml.start("entry"); + xml.elem("key", identityValue); + xml.start("value"); + xml.elem("DkimEnabled", identity != null ? String.valueOf(identity.isDkimEnabled()) : "false"); + xml.elem("DkimVerificationStatus", identity != null ? identity.getDkimVerificationStatus() : "NotStarted"); + xml.start("DkimTokens").end("DkimTokens"); + xml.end("value"); + xml.end("entry"); + } + xml.end("DkimAttributes"); + return Response.ok(AwsQueryResponse.envelope("GetIdentityDkimAttributes", AwsNamespaces.SES, xml.build())).build(); + } + + // --- Helpers --- + + private List extractMembers(MultivaluedMap params, String prefix) { + List members = new ArrayList<>(); + for (int i = 1; ; i++) { + String value = getParam(params, prefix + ".member." + i); + if (value == null) break; + members.add(value); + } + return members; + } + + private String getParam(MultivaluedMap params, String name) { + return params.getFirst(name); + } +} 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 new file mode 100644 index 0000000000..7d51c1f361 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java @@ -0,0 +1,183 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.ses.model.Identity; +import io.github.hectorvent.floci.services.ses.model.SentEmail; +import com.fasterxml.jackson.core.type.TypeReference; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +@ApplicationScoped +public class SesService { + + private static final Logger LOG = Logger.getLogger(SesService.class); + + private final StorageBackend identityStore; + private final StorageBackend emailStore; + private final RegionResolver regionResolver; + + @Inject + public SesService(StorageFactory storageFactory, EmulatorConfig config, + RegionResolver regionResolver) { + this.identityStore = storageFactory.create("ses", "ses-identities.json", + new TypeReference>() {}); + this.emailStore = storageFactory.create("ses", "ses-emails.json", + new TypeReference>() {}); + this.regionResolver = regionResolver; + } + + SesService(StorageBackend identityStore, + StorageBackend emailStore, + RegionResolver regionResolver) { + this.identityStore = identityStore; + this.emailStore = emailStore; + this.regionResolver = regionResolver; + } + + public Identity verifyEmailIdentity(String emailAddress, String region) { + if (emailAddress == null || emailAddress.isBlank()) { + throw new AwsException("InvalidParameterValue", "Email address is required.", 400); + } + String key = identityKey(region, emailAddress); + Identity existing = identityStore.get(key).orElse(null); + if (existing != null) return existing; + + Identity identity = new Identity(emailAddress, "EmailAddress"); + identityStore.put(key, identity); + LOG.infov("Verified email identity: {0} in region {1}", emailAddress, region); + return identity; + } + + public Identity verifyDomainIdentity(String domain, String region) { + if (domain == null || domain.isBlank()) { + throw new AwsException("InvalidParameterValue", "Domain is required.", 400); + } + String key = identityKey(region, domain); + Identity existing = identityStore.get(key).orElse(null); + if (existing != null) return existing; + + Identity identity = new Identity(domain, "Domain"); + identityStore.put(key, identity); + LOG.infov("Verified domain identity: {0} in region {1}", domain, region); + return identity; + } + + public void deleteIdentity(String identityValue, String region) { + String key = identityKey(region, identityValue); + identityStore.delete(key); + LOG.infov("Deleted identity: {0}", identityValue); + } + + public List listIdentities(String identityType, String region) { + String prefix = "identity::" + region + "::"; + List all = identityStore.scan(k -> k.startsWith(prefix)); + if (identityType == null || identityType.isBlank()) { + return all; + } + return all.stream() + .filter(i -> identityType.equals(i.getIdentityType())) + .toList(); + } + + public Identity getIdentityVerificationAttributes(String identityValue, String region) { + String key = identityKey(region, identityValue); + return identityStore.get(key).orElse(null); + } + + public String sendEmail(String source, List toAddresses, List ccAddresses, + List bccAddresses, String subject, String bodyText, + String bodyHtml, String region) { + if (source == null || source.isBlank()) { + throw new AwsException("InvalidParameterValue", "Source email is required.", 400); + } + if (toAddresses == null || toAddresses.isEmpty()) { + throw new AwsException("InvalidParameterValue", "At least one destination address is required.", 400); + } + + String messageId = UUID.randomUUID().toString(); + String body = bodyHtml != null ? bodyHtml : bodyText; + SentEmail email = new SentEmail(messageId, source, toAddresses, ccAddresses, bccAddresses, subject, body); + emailStore.put("email::" + region + "::" + messageId, email); + + LOG.infov("SES email sent: from={0}, to={1}, subject={2}, messageId={3}", + source, toAddresses, subject, messageId); + return messageId; + } + + public String sendRawEmail(String source, List destinations, String rawMessage, String region) { + String messageId = UUID.randomUUID().toString(); + SentEmail email = new SentEmail(messageId, source, + destinations != null ? destinations : Collections.emptyList(), + null, null, "(raw)", rawMessage); + emailStore.put("email::" + region + "::" + messageId, email); + + LOG.infov("SES raw email sent: from={0}, messageId={1}", source, messageId); + return messageId; + } + + public long getSentEmailCount(String region) { + String prefix = "email::" + region + "::"; + return emailStore.scan(k -> k.startsWith(prefix)).size(); + } + + public void setIdentityNotificationTopic(String identityValue, String notificationType, + String snsTopic, String region) { + String key = identityKey(region, identityValue); + Identity identity = identityStore.get(key) + .orElseThrow(() -> new AwsException("InvalidParameterValue", + "Identity does not exist: " + identityValue, 400)); + if (snsTopic != null && !snsTopic.isBlank()) { + identity.getNotificationAttributes().put(notificationType + "Topic", snsTopic); + } else { + identity.getNotificationAttributes().remove(notificationType + "Topic"); + } + identityStore.put(key, identity); + } + + public Identity getIdentityNotificationAttributes(String identityValue, String region) { + String key = identityKey(region, identityValue); + return identityStore.get(key).orElse(null); + } + + public List getVerifiedEmailAddresses(String region) { + String prefix = "identity::" + region + "::"; + List all = identityStore.scan(k -> k.startsWith(prefix)); + List emails = new ArrayList<>(); + for (Identity identity : all) { + if ("EmailAddress".equals(identity.getIdentityType()) + && "Success".equals(identity.getVerificationStatus())) { + emails.add(identity.getIdentity()); + } + } + return emails; + } + + public List getEmails(String region) { + String prefix = "email::" + region + "::"; + return emailStore.scan(k -> k.startsWith(prefix)); + } + + public void clearEmails(String region) { + String prefix = "email::" + region + "::"; + List keys = new ArrayList<>(emailStore.keys().stream() + .filter(k -> k.startsWith(prefix)) + .toList()); + keys.forEach(emailStore::delete); + LOG.infov("Cleared all SES emails in region {0}", region); + } + + private static String identityKey(String region, String identity) { + return "identity::" + region + "::" + identity; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/Identity.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/Identity.java new file mode 100644 index 0000000000..6c1cfb67c5 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/Identity.java @@ -0,0 +1,74 @@ +package io.github.hectorvent.floci.services.ses.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class Identity { + + @JsonProperty("Identity") + private String identity; + + @JsonProperty("IdentityType") + private String identityType; // "EmailAddress" or "Domain" + + @JsonProperty("VerificationStatus") + private String verificationStatus; // "Pending", "Success", "Failed", "TemporaryFailure", "NotStarted" + + @JsonProperty("VerificationToken") + private String verificationToken; + + @JsonProperty("DkimEnabled") + private boolean dkimEnabled; + + @JsonProperty("DkimVerificationStatus") + private String dkimVerificationStatus; + + @JsonProperty("NotificationAttributes") + private Map notificationAttributes = new HashMap<>(); + + @JsonProperty("CreatedAt") + private Instant createdAt; + + public Identity() {} + + public Identity(String identity, String identityType) { + this.identity = identity; + this.identityType = identityType; + this.verificationStatus = "Success"; // auto-verify in emulator + this.verificationToken = java.util.UUID.randomUUID().toString(); + this.dkimEnabled = false; + this.dkimVerificationStatus = "NotStarted"; + this.createdAt = Instant.now(); + } + + public String getIdentity() { return identity; } + public void setIdentity(String identity) { this.identity = identity; } + + public String getIdentityType() { return identityType; } + public void setIdentityType(String identityType) { this.identityType = identityType; } + + public String getVerificationStatus() { return verificationStatus; } + public void setVerificationStatus(String verificationStatus) { this.verificationStatus = verificationStatus; } + + public String getVerificationToken() { return verificationToken; } + public void setVerificationToken(String verificationToken) { this.verificationToken = verificationToken; } + + public boolean isDkimEnabled() { return dkimEnabled; } + public void setDkimEnabled(boolean dkimEnabled) { this.dkimEnabled = dkimEnabled; } + + public String getDkimVerificationStatus() { return dkimVerificationStatus; } + public void setDkimVerificationStatus(String dkimVerificationStatus) { this.dkimVerificationStatus = dkimVerificationStatus; } + + public Map getNotificationAttributes() { return notificationAttributes; } + public void setNotificationAttributes(Map notificationAttributes) { this.notificationAttributes = notificationAttributes; } + + public Instant getCreatedAt() { return createdAt; } + public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/SentEmail.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/SentEmail.java new file mode 100644 index 0000000000..123e32a9e5 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/SentEmail.java @@ -0,0 +1,76 @@ +package io.github.hectorvent.floci.services.ses.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.List; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class SentEmail { + + @JsonProperty("MessageId") + private String messageId; + + @JsonProperty("Source") + private String source; + + @JsonProperty("Destination") + private List toAddresses; + + @JsonProperty("CcAddresses") + private List ccAddresses; + + @JsonProperty("BccAddresses") + private List bccAddresses; + + @JsonProperty("Subject") + private String subject; + + @JsonProperty("Body") + private String body; + + @JsonProperty("SentAt") + private Instant sentAt; + + public SentEmail() {} + + public SentEmail(String messageId, String source, List toAddresses, + List ccAddresses, List bccAddresses, + String subject, String body) { + this.messageId = messageId; + this.source = source; + this.toAddresses = toAddresses; + this.ccAddresses = ccAddresses; + this.bccAddresses = bccAddresses; + this.subject = subject; + this.body = body; + this.sentAt = Instant.now(); + } + + public String getMessageId() { return messageId; } + public void setMessageId(String messageId) { this.messageId = messageId; } + + public String getSource() { return source; } + public void setSource(String source) { this.source = source; } + + public List getToAddresses() { return toAddresses; } + public void setToAddresses(List toAddresses) { this.toAddresses = toAddresses; } + + public List getCcAddresses() { return ccAddresses; } + public void setCcAddresses(List ccAddresses) { this.ccAddresses = ccAddresses; } + + public List getBccAddresses() { return bccAddresses; } + public void setBccAddresses(List bccAddresses) { this.bccAddresses = bccAddresses; } + + public String getSubject() { return subject; } + public void setSubject(String subject) { this.subject = subject; } + + public String getBody() { return body; } + public void setBody(String body) { this.body = body; } + + public Instant getSentAt() { return sentAt; } + public void setSentAt(Instant sentAt) { this.sentAt = sentAt; } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 09a87e13dd..15585b4302 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -124,3 +124,5 @@ floci: acm: enabled: true validation-wait-seconds: 0 + ses: + enabled: true diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesIntegrationTest.java new file mode 100644 index 0000000000..06e456e667 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesIntegrationTest.java @@ -0,0 +1,350 @@ +package io.github.hectorvent.floci.services.ses; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; + +/** + * Integration tests for SES via the query (form-encoded) protocol. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesIntegrationTest { + + @Test + @Order(1) + void verifyEmailIdentity() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "VerifyEmailIdentity") + .formParam("EmailAddress", "sender@example.com") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("VerifyEmailIdentityResponse")); + } + + @Test + @Order(2) + void verifyEmailIdentity_second() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "VerifyEmailIdentity") + .formParam("EmailAddress", "recipient@example.com") + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + @Order(3) + void verifyDomainIdentity() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "VerifyDomainIdentity") + .formParam("Domain", "example.com") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")); + } + + @Test + @Order(4) + void listIdentities() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "ListIdentities") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("sender@example.com")) + .body(containsString("recipient@example.com")) + .body(containsString("example.com")); + } + + @Test + @Order(5) + void listIdentities_filteredByType() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "ListIdentities") + .formParam("IdentityType", "Domain") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("example.com")) + .body(not(containsString("sender@example.com"))); + } + + @Test + @Order(6) + void getIdentityVerificationAttributes() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "GetIdentityVerificationAttributes") + .formParam("Identities.member.1", "sender@example.com") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("sender@example.com")) + .body(containsString("Success")); + } + + @Test + @Order(7) + void getIdentityVerificationAttributes_unknownIdentity() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "GetIdentityVerificationAttributes") + .formParam("Identities.member.1", "unknown@example.com") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("NotStarted")); + } + + @Test + @Order(8) + void listVerifiedEmailAddresses() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "ListVerifiedEmailAddresses") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("sender@example.com")) + .body(containsString("recipient@example.com")); + } + + @Test + @Order(9) + void sendEmail() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "SendEmail") + .formParam("Source", "sender@example.com") + .formParam("Destination.ToAddresses.member.1", "recipient@example.com") + .formParam("Message.Subject.Data", "Test Subject") + .formParam("Message.Body.Text.Data", "Hello from SES!") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")); + } + + @Test + @Order(10) + void sendEmail_withHtmlBody() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "SendEmail") + .formParam("Source", "sender@example.com") + .formParam("Destination.ToAddresses.member.1", "recipient@example.com") + .formParam("Message.Subject.Data", "HTML Test") + .formParam("Message.Body.Html.Data", "

Hello

") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")); + } + + @Test + @Order(11) + void sendRawEmail() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "SendRawEmail") + .formParam("Source", "sender@example.com") + .formParam("Destinations.member.1", "recipient@example.com") + .formParam("RawMessage.Data", "Subject: Test\r\n\r\nRaw body") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")); + } + + @Test + @Order(12) + void getSendQuota() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "GetSendQuota") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")) + .body(containsString("")) + .body(containsString("")); + } + + @Test + @Order(13) + void getSendStatistics() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "GetSendStatistics") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")) + .body(containsString("")); + } + + @Test + @Order(14) + void getAccountSendingEnabled() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "GetAccountSendingEnabled") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("true")); + } + + @Test + @Order(15) + void getIdentityDkimAttributes() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "GetIdentityDkimAttributes") + .formParam("Identities.member.1", "example.com") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("example.com")) + .body(containsString("")); + } + + @Test + @Order(16) + void setIdentityNotificationTopic() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "SetIdentityNotificationTopic") + .formParam("Identity", "sender@example.com") + .formParam("NotificationType", "Bounce") + .formParam("SnsTopic", "arn:aws:sns:us-east-1:000000000000:bounce-topic") + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + @Order(17) + void getIdentityNotificationAttributes() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "GetIdentityNotificationAttributes") + .formParam("Identities.member.1", "sender@example.com") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("sender@example.com")) + .body(containsString("bounce-topic")); + } + + @Test + @Order(18) + void deleteVerifiedEmailAddress() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "DeleteVerifiedEmailAddress") + .formParam("EmailAddress", "recipient@example.com") + .when() + .post("/") + .then() + .statusCode(200); + + // Verify it's gone + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "ListVerifiedEmailAddresses") + .when() + .post("/") + .then() + .statusCode(200) + .body(not(containsString("recipient@example.com"))); + } + + @Test + @Order(19) + void deleteIdentity() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "DeleteIdentity") + .formParam("Identity", "sender@example.com") + .when() + .post("/") + .then() + .statusCode(200); + + // Verify it's gone + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "ListIdentities") + .when() + .post("/") + .then() + .statusCode(200) + .body(not(containsString("sender@example.com"))); + } + + @Test + @Order(20) + void unsupportedAction_returns400() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "UnknownSesAction") + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("UnsupportedOperation")); + } +}