diff --git a/AGENT.md b/AGENT.md index 4014ed8310..f90f755fa4 100644 --- a/AGENT.md +++ b/AGENT.md @@ -97,7 +97,7 @@ Floci must implement real AWS wire protocols. |----------|----------|----------------|-----------------|----------------| | Query | SQS, SNS, IAM, STS, RDS, ElastiCache, CloudFormation, CloudWatch Metrics | form-encoded POST + `Action` | XML | `AwsQueryController` | | JSON 1.1 | SSM, EventBridge, CloudWatch Logs, Kinesis, KMS, Cognito, Secrets Manager, ACM | POST + `X-Amz-Target` | JSON | `AwsJson11Controller` | -| REST JSON | Lambda, API Gateway | REST paths | JSON | JAX-RS | +| REST JSON | Lambda, API Gateway, SES V2 | REST paths | JSON | JAX-RS | | REST XML | S3 | REST paths | XML | JAX-RS | | TCP | ElastiCache, RDS | raw protocol | native | proxies | diff --git a/README.md b/README.md index 754c4de127..df4041a8e1 100644 --- a/README.md +++ b/README.md @@ -119,6 +119,7 @@ flowchart LR | **EC2** | 61 | In-process | VPCs, subnets, security groups, instances, AMIs, key pairs, internet gateways, route tables, Elastic IPs, tags | | **ACM** | 8 | In-process | Certificate issuance, validation lifecycle | | **SES** | 14 | In-process | Send email / raw email, identity verification, DKIM attributes | +| **SES v2 (HTTP)** | 9 | In-process | REST JSON API, identities, DKIM, feedback attributes, account sending | | **OpenSearch** | 24 | In-process | Domain CRUD, tags, versions, instance types, upgrade stubs | > **Lambda, ElastiCache, RDS, and ECS** spin up real Docker containers and support IAM authentication and SigV4 request signing — the same auth flow as production AWS. diff --git a/docs/index.md b/docs/index.md index 9fcc87fcad..a989289a1e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -17,7 +17,7 @@ Floci is a fast, free, and open-source local AWS service emulator built for deve | SSM Parameter Store | JSON 1.1 | | SQS | Query / JSON | | SNS | Query / JSON | -| SES | Query | +| SES | Query / REST JSON | | S3 | REST XML | | DynamoDB + Streams | JSON 1.1 | | Lambda | REST JSON | diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java index 1e63af3d18..8546b0f390 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ServiceEnabledFilter.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.core.common; import io.github.hectorvent.floci.services.cognito.CognitoOAuthController; import io.github.hectorvent.floci.services.cognito.CognitoWellKnownController; +import io.github.hectorvent.floci.services.ses.SesController; import jakarta.inject.Inject; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.container.ContainerRequestFilter; @@ -78,6 +79,7 @@ public class ServiceEnabledFilter implements ContainerRequestFilter { private String mapCredentialScope(String scope) { return switch (scope) { case "execute-api" -> "apigateway"; + case "ses", "sesv2" -> "email"; default -> scope; }; } @@ -91,6 +93,9 @@ public class ServiceEnabledFilter implements ContainerRequestFilter { || CognitoWellKnownController.class.equals(resourceClass)) { return "cognito-idp"; } + if (SesController.class.equals(resourceClass)) { + return "email"; + } return null; } @@ -99,8 +104,10 @@ public class ServiceEnabledFilter implements ContainerRequestFilter { String target = ctx.getHeaderString("X-Amz-Target"); String contentType = ctx.getMediaType() != null ? ctx.getMediaType().toString() : ""; boolean jsonEndpoint = serviceKeyFromMatchedResource() != null; + String accept = ctx.getHeaderString("Accept"); + boolean acceptsJson = accept != null && accept.contains("json"); - if (target != null || contentType.contains("json") || jsonEndpoint) { + if (target != null || contentType.contains("json") || jsonEndpoint || acceptsJson) { return Response.status(400) .type(MediaType.APPLICATION_JSON) .entity(new AwsErrorResponse("ServiceNotAvailableException", message)) diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java new file mode 100644 index 0000000000..1547fde1b5 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java @@ -0,0 +1,362 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.ses.model.Identity; +import com.fasterxml.jackson.databind.JsonNode; +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.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import org.jboss.logging.Logger; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * REST JSON controller for the AWS SES V2 API. + * Implements the AWS SES V2 wire protocol at /v2/email/* for the operations + * exposed by this controller. + * Reuses the shared {@link SesService} for business logic shared with other SES + * protocol handlers. + * + * Follows the same pattern as {@code LambdaController}: AwsExceptions are thrown + * directly and converted by the global {@code AwsExceptionMapper}. + */ +@Path("/v2/email") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class SesController { + + private static final Logger LOG = Logger.getLogger(SesController.class); + + private final SesService sesService; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public SesController(SesService sesService, RegionResolver regionResolver, + ObjectMapper objectMapper) { + this.sesService = sesService; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + // ──────────────────────────── Identities ──────────────────────────── + + @POST + @Path("/identities") + public Response createEmailIdentity(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode request = objectMapper.readTree(body); + String emailIdentity = request.path("EmailIdentity").asText(null); + if (emailIdentity == null || emailIdentity.isBlank()) { + throw new AwsException("BadRequestException", "EmailIdentity is required.", 400); + } + + Identity identity = emailIdentity.contains("@") + ? sesService.verifyEmailIdentity(emailIdentity, region) + : sesService.verifyDomainIdentity(emailIdentity, region); + + ObjectNode result = objectMapper.createObjectNode(); + result.put("IdentityType", toV2IdentityType(identity.getIdentityType())); + result.put("VerifiedForSendingStatus", true); + result.set("DkimAttributes", buildDkimAttributes(identity)); + + LOG.infov("SES V2 CreateEmailIdentity: {0}", emailIdentity); + return Response.ok(result).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (Exception e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + + @GET + @Path("/identities") + public Response listEmailIdentities(@Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + List identities = sesService.listIdentities(null, region); + + ObjectNode result = objectMapper.createObjectNode(); + ArrayNode items = result.putArray("EmailIdentities"); + for (Identity id : identities) { + ObjectNode item = objectMapper.createObjectNode(); + item.put("IdentityType", toV2IdentityType(id.getIdentityType())); + item.put("IdentityName", id.getIdentity()); + item.put("SendingEnabled", true); + items.add(item); + } + return Response.ok(result).build(); + } + + @GET + @Path("/identities/{emailIdentity}") + public Response getEmailIdentity(@Context HttpHeaders headers, + @PathParam("emailIdentity") String emailIdentity) { + String region = regionResolver.resolveRegion(headers); + Identity identity = sesService.getIdentityVerificationAttributes(emailIdentity, region); + if (identity == null) { + throw new AwsException("NotFoundException", + "Identity " + emailIdentity + " does not exist.", 404); + } + return Response.ok(buildFullIdentityResponse(identity)).build(); + } + + @DELETE + @Path("/identities/{emailIdentity}") + public Response deleteEmailIdentity(@Context HttpHeaders headers, + @PathParam("emailIdentity") String emailIdentity) { + String region = regionResolver.resolveRegion(headers); + sesService.deleteIdentity(emailIdentity, region); + LOG.infov("SES V2 DeleteEmailIdentity: {0}", emailIdentity); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + // ──────────────────────── Identity DKIM ───────────────────────── + + @PUT + @Path("/identities/{emailIdentity}/dkim") + public Response putEmailIdentityDkimAttributes(@Context HttpHeaders headers, + @PathParam("emailIdentity") String emailIdentity, + String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode request = objectMapper.readTree(body); + JsonNode signingEnabledNode = request.get("SigningEnabled"); + if (signingEnabledNode == null || !signingEnabledNode.isBoolean()) { + throw new AwsException("BadRequestException", + "SigningEnabled must be present and must be a boolean", 400); + } + boolean signingEnabled = signingEnabledNode.booleanValue(); + sesService.setDkimAttributes(emailIdentity, signingEnabled, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (Exception e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + + // ──────────────────── Identity Feedback ───────────────────────── + + @PUT + @Path("/identities/{emailIdentity}/feedback") + public Response putEmailIdentityFeedbackAttributes(@Context HttpHeaders headers, + @PathParam("emailIdentity") String emailIdentity, + String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode request = objectMapper.readTree(body); + JsonNode emailForwardingEnabledNode = request.get("EmailForwardingEnabled"); + if (emailForwardingEnabledNode == null || !emailForwardingEnabledNode.isBoolean()) { + throw new AwsException("BadRequestException", + "EmailForwardingEnabled must be present and must be a boolean", 400); + } + boolean emailForwardingEnabled = emailForwardingEnabledNode.booleanValue(); + sesService.setFeedbackForwardingEnabled(emailIdentity, emailForwardingEnabled, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (Exception e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + + // ──────────────────────────── Send Email ──────────────────────────── + + @POST + @Path("/outbound-emails") + public Response sendEmail(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + try { + if (!sesService.isAccountSendingEnabled(region)) { + throw new AwsException("SendingPausedException", + "Account sending is disabled.", 400); + } + + JsonNode request = objectMapper.readTree(body); + + String fromEmailAddress = request.path("FromEmailAddress").asText(null); + if (fromEmailAddress == null || fromEmailAddress.isBlank()) { + throw new AwsException("BadRequestException", + "FromEmailAddress is required.", 400); + } + + JsonNode destination = request.path("Destination"); + List toAddresses = jsonArrayToList(destination.path("ToAddresses")); + List ccAddresses = jsonArrayToList(destination.path("CcAddresses")); + List bccAddresses = jsonArrayToList(destination.path("BccAddresses")); + + JsonNode content = request.path("Content"); + String messageId; + + if (content.has("Raw")) { + String rawData = content.path("Raw").path("Data").asText(null); + if (rawData == null || rawData.isBlank()) { + throw new AwsException("BadRequestException", + "Content.Raw.Data is required.", 400); + } + List allDestinations = mergeLists(toAddresses, ccAddresses, bccAddresses); + if (allDestinations.isEmpty()) { + throw new AwsException("BadRequestException", + "At least one destination address is required.", 400); + } + messageId = sesService.sendRawEmail(fromEmailAddress, allDestinations, rawData, region); + } else if (content.has("Simple")) { + JsonNode simple = content.path("Simple"); + String subject = simple.path("Subject").path("Data").asText(""); + String bodyText = simple.path("Body").path("Text").path("Data").asText(null); + String bodyHtml = simple.path("Body").path("Html").path("Data").asText(null); + messageId = sesService.sendEmail(fromEmailAddress, toAddresses, ccAddresses, + bccAddresses, subject, bodyText, bodyHtml, region); + } else if (content.has("Template")) { + String subject = content.path("Template").path("TemplateName").asText("(template)"); + String templateData = content.path("Template").path("TemplateData").asText(""); + messageId = sesService.sendEmail(fromEmailAddress, toAddresses, ccAddresses, + bccAddresses, subject, templateData, null, region); + } else { + throw new AwsException("BadRequestException", + "Content must contain Raw, Simple, or Template.", 400); + } + + ObjectNode result = objectMapper.createObjectNode(); + result.put("MessageId", messageId); + + LOG.infov("SES V2 SendEmail: from={0}, to={1}, messageId={2}", + fromEmailAddress, toAddresses, messageId); + return Response.ok(result).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (Exception e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + + // ──────────────────────────── Account ──────────────────────────── + + @GET + @Path("/account") + public Response getAccount(@Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + long sentCount = sesService.getSentEmailCount(region); + boolean sendingEnabled = sesService.isAccountSendingEnabled(region); + + ObjectNode result = objectMapper.createObjectNode(); + result.put("DedicatedIpAutoWarmupEnabled", false); + result.put("EnforcementStatus", "HEALTHY"); + result.put("ProductionAccessEnabled", true); + result.put("SendingEnabled", sendingEnabled); + + ObjectNode sendQuota = result.putObject("SendQuota"); + sendQuota.put("Max24HourSend", 200.0); + sendQuota.put("MaxSendRate", 1.0); + sendQuota.put("SentLast24Hours", (double) sentCount); + + return Response.ok(result).build(); + } + + @PUT + @Path("/account/sending") + public Response putAccountSendingAttributes(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode request = objectMapper.readTree(body); + JsonNode sendingEnabledNode = request.get("SendingEnabled"); + if (sendingEnabledNode == null || !sendingEnabledNode.isBoolean()) { + throw new AwsException("BadRequestException", + "SendingEnabled must be present and must be a boolean", 400); + } + sesService.setAccountSendingEnabled(region, sendingEnabledNode.booleanValue()); + return Response.ok(objectMapper.createObjectNode()).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (Exception e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + + // ──────────────────────────── Helpers ──────────────────────────── + + private ObjectNode buildFullIdentityResponse(Identity identity) { + ObjectNode result = objectMapper.createObjectNode(); + result.put("IdentityType", toV2IdentityType(identity.getIdentityType())); + result.put("VerifiedForSendingStatus", + "Success".equals(identity.getVerificationStatus())); + result.put("VerificationStatus", toV2Status(identity.getVerificationStatus())); + result.put("FeedbackForwardingStatus", identity.isFeedbackForwardingEnabled()); + + result.set("DkimAttributes", buildDkimAttributes(identity)); + + ObjectNode mailFromAttributes = result.putObject("MailFromAttributes"); + mailFromAttributes.put("MailFromDomain", ""); + mailFromAttributes.put("MailFromDomainStatus", "NOT_STARTED"); + mailFromAttributes.put("BehaviorOnMxFailure", "USE_DEFAULT_VALUE"); + + result.putObject("Policies"); + result.putArray("Tags"); + + return result; + } + + private ObjectNode buildDkimAttributes(Identity identity) { + ObjectNode dkim = objectMapper.createObjectNode(); + dkim.put("SigningEnabled", identity.isDkimEnabled()); + dkim.put("Status", toV2Status(identity.getDkimVerificationStatus())); + dkim.putArray("Tokens"); + return dkim; + } + + private static String toV2IdentityType(String v1Type) { + return "EmailAddress".equals(v1Type) ? "EMAIL_ADDRESS" : "DOMAIN"; + } + + private static String toV2Status(String v1Status) { + if (v1Status == null) return null; + return switch (v1Status) { + case "Success" -> "SUCCESS"; + case "NotStarted" -> "NOT_STARTED"; + case "Pending" -> "PENDING"; + case "Failed" -> "FAILED"; + case "TemporaryFailure" -> "TEMPORARY_FAILURE"; + default -> v1Status; + }; + } + + private List jsonArrayToList(JsonNode arrayNode) { + if (arrayNode == null || arrayNode.isMissingNode() || !arrayNode.isArray()) { + return Collections.emptyList(); + } + List list = new ArrayList<>(); + arrayNode.forEach(node -> list.add(node.asText())); + return list; + } + + private List mergeLists(List to, List cc, List bcc) { + List all = new ArrayList<>(to); + all.addAll(cc); + all.addAll(bcc); + return all; + } + + private static AwsException remapV1Exception(AwsException e) { + if ("InvalidParameterValue".equals(e.getErrorCode())) { + return new AwsException("BadRequestException", e.getMessage(), 400); + } + return e; + } +} 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 index 3499c09d93..a8cd2140e4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java @@ -45,7 +45,7 @@ public class SesQueryHandler { case "SendRawEmail" -> handleSendRawEmail(params, region); case "GetSendQuota" -> handleGetSendQuota(region); case "GetSendStatistics" -> handleGetSendStatistics(region); - case "GetAccountSendingEnabled" -> handleGetAccountSendingEnabled(); + case "GetAccountSendingEnabled" -> handleGetAccountSendingEnabled(region); case "ListVerifiedEmailAddresses" -> handleListVerifiedEmailAddresses(region); case "DeleteVerifiedEmailAddress" -> handleDeleteVerifiedEmailAddress(params, region); case "SetIdentityNotificationTopic" -> handleSetIdentityNotificationTopic(params, region); @@ -171,8 +171,9 @@ public class SesQueryHandler { return Response.ok(AwsQueryResponse.envelope("GetSendStatistics", AwsNamespaces.SES, xml.build())).build(); } - private Response handleGetAccountSendingEnabled() { - String result = new XmlBuilder().elem("Enabled", "true").build(); + private Response handleGetAccountSendingEnabled(String region) { + boolean enabled = sesService.isAccountSendingEnabled(region); + String result = new XmlBuilder().elem("Enabled", String.valueOf(enabled)).build(); return Response.ok(AwsQueryResponse.envelope("GetAccountSendingEnabled", AwsNamespaces.SES, result)).build(); } 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 7d51c1f361..6e3c2c9858 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 @@ -25,6 +25,7 @@ public class SesService { private final StorageBackend identityStore; private final StorageBackend emailStore; + private final StorageBackend accountSettingsStore; private final RegionResolver regionResolver; @Inject @@ -34,14 +35,18 @@ public class SesService { new TypeReference>() {}); this.emailStore = storageFactory.create("ses", "ses-emails.json", new TypeReference>() {}); + this.accountSettingsStore = storageFactory.create("ses", "ses-account-settings.json", + new TypeReference>() {}); this.regionResolver = regionResolver; } SesService(StorageBackend identityStore, StorageBackend emailStore, + StorageBackend accountSettingsStore, RegionResolver regionResolver) { this.identityStore = identityStore; this.emailStore = emailStore; + this.accountSettingsStore = accountSettingsStore; this.regionResolver = regionResolver; } @@ -101,7 +106,10 @@ public class SesService { if (source == null || source.isBlank()) { throw new AwsException("InvalidParameterValue", "Source email is required.", 400); } - if (toAddresses == null || toAddresses.isEmpty()) { + boolean hasRecipient = (toAddresses != null && !toAddresses.isEmpty()) + || (ccAddresses != null && !ccAddresses.isEmpty()) + || (bccAddresses != null && !bccAddresses.isEmpty()); + if (!hasRecipient) { throw new AwsException("InvalidParameterValue", "At least one destination address is required.", 400); } @@ -150,6 +158,31 @@ public class SesService { return identityStore.get(key).orElse(null); } + public void setDkimAttributes(String identityValue, boolean signingEnabled, String region) { + String key = identityKey(region, identityValue); + Identity identity = identityStore.get(key) + .orElseThrow(() -> new AwsException("NotFoundException", + "Identity does not exist: " + identityValue, 404)); + identity.setDkimEnabled(signingEnabled); + if (signingEnabled) { + identity.setDkimVerificationStatus("Success"); + } else { + identity.setDkimVerificationStatus("NotStarted"); + } + identityStore.put(key, identity); + LOG.infov("Updated DKIM attributes for {0}: signingEnabled={1}", identityValue, signingEnabled); + } + + public void setFeedbackForwardingEnabled(String identityValue, boolean enabled, String region) { + String key = identityKey(region, identityValue); + Identity identity = identityStore.get(key) + .orElseThrow(() -> new AwsException("NotFoundException", + "Identity does not exist: " + identityValue, 404)); + identity.setFeedbackForwardingEnabled(enabled); + identityStore.put(key, identity); + LOG.infov("Updated feedback forwarding for {0}: enabled={1}", identityValue, enabled); + } + public List getVerifiedEmailAddresses(String region) { String prefix = "identity::" + region + "::"; List all = identityStore.scan(k -> k.startsWith(prefix)); @@ -177,6 +210,15 @@ public class SesService { LOG.infov("Cleared all SES emails in region {0}", region); } + public boolean isAccountSendingEnabled(String region) { + return accountSettingsStore.get("sending::" + region).orElse(true); + } + + public void setAccountSendingEnabled(String region, boolean enabled) { + accountSettingsStore.put("sending::" + region, enabled); + LOG.infov("Updated account sending enabled for region {0}: {1}", region, enabled); + } + 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 index 6c1cfb67c5..0aadf25ee4 100644 --- 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 @@ -33,6 +33,9 @@ public class Identity { @JsonProperty("NotificationAttributes") private Map notificationAttributes = new HashMap<>(); + @JsonProperty("FeedbackForwardingEnabled") + private boolean feedbackForwardingEnabled = true; + @JsonProperty("CreatedAt") private Instant createdAt; @@ -69,6 +72,9 @@ public class Identity { public Map getNotificationAttributes() { return notificationAttributes; } public void setNotificationAttributes(Map notificationAttributes) { this.notificationAttributes = notificationAttributes; } + public boolean isFeedbackForwardingEnabled() { return feedbackForwardingEnabled; } + public void setFeedbackForwardingEnabled(boolean feedbackForwardingEnabled) { this.feedbackForwardingEnabled = feedbackForwardingEnabled; } + public Instant getCreatedAt() { return createdAt; } public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } } diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2IntegrationTest.java new file mode 100644 index 0000000000..508ed61b1d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2IntegrationTest.java @@ -0,0 +1,645 @@ +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 V2 via the REST JSON protocol. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesV2IntegrationTest { + + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request"; + + @Test + @Order(1) + void createEmailIdentity_email() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"EmailIdentity": "v2sender@example.com"} + """) + .when() + .post("/v2/email/identities") + .then() + .statusCode(200) + .body("IdentityType", equalTo("EMAIL_ADDRESS")) + .body("VerifiedForSendingStatus", equalTo(true)); + } + + @Test + @Order(2) + void createEmailIdentity_domain() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"EmailIdentity": "v2example.com"} + """) + .when() + .post("/v2/email/identities") + .then() + .statusCode(200) + .body("IdentityType", equalTo("DOMAIN")); + } + + @Test + @Order(3) + void createEmailIdentity_missingField() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body("{}") + .when() + .post("/v2/email/identities") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")); + } + + @Test + @Order(4) + void listEmailIdentities() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/identities") + .then() + .statusCode(200) + .body("EmailIdentities", notNullValue()) + .body("EmailIdentities.size()", greaterThanOrEqualTo(2)) + .body("EmailIdentities.IdentityName", hasItem("v2sender@example.com")) + .body("EmailIdentities.IdentityName", hasItem("v2example.com")); + } + + @Test + @Order(5) + void getEmailIdentity() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/identities/v2sender@example.com") + .then() + .statusCode(200) + .body("IdentityType", equalTo("EMAIL_ADDRESS")) + .body("VerifiedForSendingStatus", equalTo(true)) + .body("DkimAttributes", notNullValue()); + } + + @Test + @Order(6) + void getEmailIdentity_notFound() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/identities/nonexistent@example.com") + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")); + } + + @Test + @Order(7) + void sendEmail_simple() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { + "FromEmailAddress": "v2sender@example.com", + "Destination": { + "ToAddresses": ["recipient@example.com"] + }, + "Content": { + "Simple": { + "Subject": {"Data": "V2 Test Subject"}, + "Body": { + "Text": {"Data": "Hello from SES V2!"} + } + } + } + } + """) + .when() + .post("/v2/email/outbound-emails") + .then() + .statusCode(200) + .body("MessageId", notNullValue()); + } + + @Test + @Order(8) + void sendEmail_html() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { + "FromEmailAddress": "v2sender@example.com", + "Destination": { + "ToAddresses": ["recipient@example.com"], + "CcAddresses": ["cc@example.com"] + }, + "Content": { + "Simple": { + "Subject": {"Data": "HTML V2 Test"}, + "Body": { + "Html": {"Data": "

Hello V2

"} + } + } + } + } + """) + .when() + .post("/v2/email/outbound-emails") + .then() + .statusCode(200) + .body("MessageId", notNullValue()); + } + + @Test + @Order(9) + void sendEmail_raw() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { + "FromEmailAddress": "v2sender@example.com", + "Destination": { + "ToAddresses": ["recipient@example.com"] + }, + "Content": { + "Raw": { + "Data": "Subject: Raw V2\\r\\n\\r\\nRaw body" + } + } + } + """) + .when() + .post("/v2/email/outbound-emails") + .then() + .statusCode(200) + .body("MessageId", notNullValue()); + } + + @Test + @Order(10) + void sendEmail_missingContent() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { + "FromEmailAddress": "v2sender@example.com", + "Destination": { + "ToAddresses": ["recipient@example.com"] + }, + "Content": {} + } + """) + .when() + .post("/v2/email/outbound-emails") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")); + } + + @Test + @Order(11) + void getAccount() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/account") + .then() + .statusCode(200) + .body("SendingEnabled", equalTo(true)) + .body("ProductionAccessEnabled", equalTo(true)) + .body("SendQuota.Max24HourSend", notNullValue()) + .body("SendQuota.MaxSendRate", notNullValue()) + .body("SendQuota.SentLast24Hours", notNullValue()); + } + + @Test + @Order(12) + void deleteEmailIdentity() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .when() + .delete("/v2/email/identities/v2sender@example.com") + .then() + .statusCode(200) + .contentType(containsString("application/json")) + .body("size()", equalTo(0)); // empty JSON object {} + + // Verify it's gone + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/identities/v2sender@example.com") + .then() + .statusCode(404); + } + + @Test + @Order(13) + void sendEmail_template() { + // Re-create an identity for template test + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"EmailIdentity": "template-sender@example.com"} + """) + .when() + .post("/v2/email/identities") + .then() + .statusCode(200); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { + "FromEmailAddress": "template-sender@example.com", + "Destination": { + "ToAddresses": ["recipient@example.com"] + }, + "Content": { + "Template": { + "TemplateName": "MyTemplate", + "TemplateData": "{\\"name\\": \\"World\\"}" + } + } + } + """) + .when() + .post("/v2/email/outbound-emails") + .then() + .statusCode(200) + .body("MessageId", notNullValue()); + } + + // ──────────────── DKIM Attributes ──────────────── + + @Test + @Order(20) + void putDkimAttributes_enable() { + // Create identity first + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"EmailIdentity": "dkim-test@example.com"} + """) + .when() + .post("/v2/email/identities") + .then() + .statusCode(200); + + // Enable DKIM + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"SigningEnabled": true} + """) + .when() + .put("/v2/email/identities/dkim-test@example.com/dkim") + .then() + .statusCode(200); + + // Verify DKIM is enabled on the identity + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/identities/dkim-test@example.com") + .then() + .statusCode(200) + .body("DkimAttributes.SigningEnabled", equalTo(true)) + .body("DkimAttributes.Status", equalTo("SUCCESS")); + } + + @Test + @Order(21) + void putDkimAttributes_disable() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"SigningEnabled": false} + """) + .when() + .put("/v2/email/identities/dkim-test@example.com/dkim") + .then() + .statusCode(200); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/identities/dkim-test@example.com") + .then() + .statusCode(200) + .body("DkimAttributes.SigningEnabled", equalTo(false)) + .body("DkimAttributes.Status", equalTo("NOT_STARTED")); + } + + @Test + @Order(22) + void putDkimAttributes_notFound() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"SigningEnabled": true} + """) + .when() + .put("/v2/email/identities/nonexistent@example.com/dkim") + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")); + } + + // ──────────────── Feedback Attributes ──────────────── + + @Test + @Order(40) + void putFeedbackAttributes_disable() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"EmailForwardingEnabled": false} + """) + .when() + .put("/v2/email/identities/dkim-test@example.com/feedback") + .then() + .statusCode(200); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/identities/dkim-test@example.com") + .then() + .statusCode(200) + .body("FeedbackForwardingStatus", equalTo(false)); + } + + @Test + @Order(41) + void putFeedbackAttributes_enable() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"EmailForwardingEnabled": true} + """) + .when() + .put("/v2/email/identities/dkim-test@example.com/feedback") + .then() + .statusCode(200); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/identities/dkim-test@example.com") + .then() + .statusCode(200) + .body("FeedbackForwardingStatus", equalTo(true)); + } + + @Test + @Order(42) + void putFeedbackAttributes_notFound() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"EmailForwardingEnabled": false} + """) + .when() + .put("/v2/email/identities/nonexistent@example.com/feedback") + .then() + .statusCode(404) + .body("__type", equalTo("NotFoundException")); + } + + // ──────────────── Account Sending ──────────────── + + @Test + @Order(50) + void putAccountSendingAttributes_disable() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"SendingEnabled": false} + """) + .when() + .put("/v2/email/account/sending") + .then() + .statusCode(200); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/account") + .then() + .statusCode(200) + .body("SendingEnabled", equalTo(false)); + } + + @Test + @Order(51) + void putAccountSendingAttributes_enable() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"SendingEnabled": true} + """) + .when() + .put("/v2/email/account/sending") + .then() + .statusCode(200); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/account") + .then() + .statusCode(200) + .body("SendingEnabled", equalTo(true)); + } + + @Test + @Order(52) + void putAccountSendingAttributes_missingField() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body("{}") + .when() + .put("/v2/email/account/sending") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")); + } + + @Test + @Order(57) + void sendEmail_ccOnly_noToAddresses() { + // Re-create identity + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"EmailIdentity": "cc-only-sender@example.com"} + """) + .when() + .post("/v2/email/identities") + .then() + .statusCode(200); + + // Send with only CcAddresses (no ToAddresses) + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { + "FromEmailAddress": "cc-only-sender@example.com", + "Destination": { + "CcAddresses": ["cc-recipient@example.com"] + }, + "Content": { + "Simple": { + "Subject": {"Data": "CC Only Test"}, + "Body": {"Text": {"Data": "Hello via CC"}} + } + } + } + """) + .when() + .post("/v2/email/outbound-emails") + .then() + .statusCode(200) + .body("MessageId", notNullValue()); + } + + // ──────────────── Validation edge cases ──────────────── + + @Test + @Order(53) + void putDkimAttributes_missingField() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body("{}") + .when() + .put("/v2/email/identities/dkim-test@example.com/dkim") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")); + } + + @Test + @Order(54) + void putFeedbackAttributes_missingField() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body("{}") + .when() + .put("/v2/email/identities/dkim-test@example.com/feedback") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")); + } + + @Test + @Order(55) + void sendEmail_raw_missingData() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { + "FromEmailAddress": "v2sender@example.com", + "Destination": {"ToAddresses": ["r@example.com"]}, + "Content": {"Raw": {}} + } + """) + .when() + .post("/v2/email/outbound-emails") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")); + } + + @Test + @Order(56) + void sendEmail_raw_missingFrom() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + { + "Destination": {"ToAddresses": ["r@example.com"]}, + "Content": {"Raw": {"Data": "Subject: test"}} + } + """) + .when() + .post("/v2/email/outbound-emails") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")); + } + + // ──────────────── GetEmailIdentity full response ──────────────── + + @Test + @Order(60) + void getEmailIdentity_fullResponse() { + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/identities/dkim-test@example.com") + .then() + .statusCode(200) + .body("IdentityType", equalTo("EMAIL_ADDRESS")) + .body("VerifiedForSendingStatus", equalTo(true)) + .body("VerificationStatus", equalTo("SUCCESS")) + .body("FeedbackForwardingStatus", notNullValue()) + .body("DkimAttributes", notNullValue()) + .body("DkimAttributes.SigningEnabled", notNullValue()) + .body("DkimAttributes.Status", notNullValue()) + .body("MailFromAttributes", notNullValue()) + .body("MailFromAttributes.MailFromDomainStatus", equalTo("NOT_STARTED")) + .body("MailFromAttributes.BehaviorOnMxFailure", equalTo("USE_DEFAULT_VALUE")) + .body("Policies", notNullValue()) + .body("Tags", notNullValue()); + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index d299b1461e..8248591d6a 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -96,6 +96,8 @@ floci: enabled: true cloudformation: enabled: true + ses: + enabled: true opensearch: enabled: true mode: mock