diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index 5d798189c6..6c4fd4aa96 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -39,6 +39,7 @@ import io.github.hectorvent.floci.services.ses.SesContactController; import io.github.hectorvent.floci.services.ses.SesController; import io.github.hectorvent.floci.services.ses.SesCvetController; import io.github.hectorvent.floci.services.ses.SesDedicatedIpController; +import io.github.hectorvent.floci.services.ses.SesIdentityController; import io.github.hectorvent.floci.services.ses.SesSuppressionController; import io.github.hectorvent.floci.services.ses.SesTagController; import io.github.hectorvent.floci.services.ses.SesTemplateController; @@ -298,7 +299,8 @@ public class ResolvedServiceCatalog { Set.of(SesController.class, SesAccountController.class, SesConfigurationSetController.class, SesContactController.class, SesCvetController.class, SesDedicatedIpController.class, - SesSuppressionController.class, SesTagController.class, + SesIdentityController.class, SesSuppressionController.class, + SesTagController.class, SesTemplateController.class, SesTenantController.class)), descriptor("es", "opensearch", config.services().opensearch().enabled(), true, "opensearch", storageMode(config.storage().services().opensearch().mode(), config.storage().mode()), 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 index fd45008820..8d1bc257b3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java @@ -5,7 +5,6 @@ import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.services.ses.model.BulkEmailEntry; import io.github.hectorvent.floci.services.ses.model.BulkEmailEntryResult; import io.github.hectorvent.floci.services.ses.model.EmailTemplate; -import io.github.hectorvent.floci.services.ses.model.Identity; import io.github.hectorvent.floci.services.ses.model.ListManagementOptions; import io.github.hectorvent.floci.services.ses.model.MessageHeader; import io.github.hectorvent.floci.services.ses.model.MessageTag; @@ -34,7 +33,6 @@ import java.util.Collections; import java.util.List; import java.util.Map; -import static io.github.hectorvent.floci.services.ses.SesV2Json.parseTagsArray; import static io.github.hectorvent.floci.services.ses.SesV2Json.remapV1Exception; import static io.github.hectorvent.floci.services.ses.SesV2Json.requireJsonObject; import static io.github.hectorvent.floci.services.ses.SesV2Json.requireObjectOrAbsent; @@ -76,376 +74,6 @@ public class SesController { 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); - JsonNode emailIdentityNode = request.path("EmailIdentity"); - if (!emailIdentityNode.isMissingNode() && !emailIdentityNode.isNull() - && !emailIdentityNode.isTextual()) { - // A non-string EmailIdentity is rejected rather than coerced (asText would turn 123 - // into "123"), the same as ConfigurationSetName below. - throw new AwsException("SerializationException", null, 400); - } - String emailIdentity = emailIdentityNode.asText(null); - if (emailIdentity == null || emailIdentity.isBlank()) { - throw new AwsException("BadRequestException", "EmailIdentity is required.", 400); - } - // ConfigurationSetName must be a String; AWS rejects a non-string, so reject it here too - // rather than coercing via asText (which would turn 123 into "123"). Floci surfaces this - // as a 400 SerializationException, rendered as a JSON error body by AwsExceptionMapper. - JsonNode configSetNode = request.path("ConfigurationSetName"); - String configurationSetName = null; - if (!configSetNode.isMissingNode() && !configSetNode.isNull()) { - if (!configSetNode.isTextual()) { - throw new AwsException("SerializationException", null, 400); - } - configurationSetName = configSetNode.textValue(); - } - - List parsedTags = parseTagsArray(request.path("Tags")); - - // Only the empty string means "no default configuration set" (consistent with the - // PutEmailIdentityConfigurationSetAttributes path); a whitespace-only name flows through - // name validation and is rejected as invalid input, rather than being silently ignored. - boolean hasConfigSet = configurationSetName != null && !configurationSetName.isEmpty(); - - // The service builds the complete identity (default configuration set and tags included) - // and persists it with a single write, so any failure (AlreadyExists, invalid tags, a - // missing configuration set) fails the whole call and creates nothing, matching AWS. - Identity identity = sesService.createEmailIdentity(emailIdentity, - hasConfigSet ? configurationSetName : null, parsedTags, region); - - ObjectNode result = objectMapper.createObjectNode(); - result.put("IdentityType", toV2IdentityType(identity.getIdentityType())); - result.put("VerifiedForSendingStatus", - "Success".equals(identity.getVerificationStatus())); - result.set("DkimAttributes", buildDkimAttributes(identity, region)); - - 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) { - // Only a not-yet-verified domain can still transition (via its DKIM records), - // so refresh just those; refreshing every identity would scan Route53 per call. - Identity current = id; - if ("Domain".equals(id.getIdentityType()) && !"Success".equals(id.getVerificationStatus())) { - Identity refreshed = sesService.getIdentityVerificationAttributes(id.getIdentity(), region); - if (refreshed != null) { - current = refreshed; - } - } - ObjectNode item = objectMapper.createObjectNode(); - item.put("IdentityType", toV2IdentityType(current.getIdentityType())); - item.put("IdentityName", current.getIdentity()); - item.put("SendingEnabled", "Success".equals(current.getVerificationStatus())); - item.put("VerificationStatus", toV2Status(current.getVerificationStatus())); - 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, region)).build(); - } - - @DELETE - @Path("/identities/{emailIdentity}") - public Response deleteEmailIdentity(@Context HttpHeaders headers, - @PathParam("emailIdentity") String emailIdentity) { - String region = regionResolver.resolveRegion(headers); - if (sesService.getIdentityVerificationAttributes(emailIdentity, region) == null) { - throw new AwsException("NotFoundException", - "Email identity " + emailIdentity + " does not exist.", 404); - } - sesService.deleteIdentity(emailIdentity, region); - LOG.infov("SES V2 DeleteEmailIdentity: {0}", emailIdentity); - return Response.ok(objectMapper.createObjectNode()).build(); - } - - // ────────────────── Identity policies (sending authorization) ──────────────── - - @POST - @Path("/identities/{emailIdentity}/policies/{policyName}") - public Response createEmailIdentityPolicy(@Context HttpHeaders headers, - @PathParam("emailIdentity") String emailIdentity, - @PathParam("policyName") String policyName, String body) { - String region = regionResolver.resolveRegion(headers); - try { - String policy = readPolicyBody(body); - sesService.createEmailIdentityPolicy(emailIdentity, policyName, policy, region); - return Response.ok(objectMapper.createObjectNode()).build(); - } catch (AwsException e) { - throw remapV1Exception(e); - } catch (com.fasterxml.jackson.core.JsonProcessingException e) { - throw new AwsException("BadRequestException", e.getMessage(), 400); - } - } - - @PUT - @Path("/identities/{emailIdentity}/policies/{policyName}") - public Response updateEmailIdentityPolicy(@Context HttpHeaders headers, - @PathParam("emailIdentity") String emailIdentity, - @PathParam("policyName") String policyName, String body) { - String region = regionResolver.resolveRegion(headers); - try { - String policy = readPolicyBody(body); - sesService.updateEmailIdentityPolicy(emailIdentity, policyName, policy, region); - return Response.ok(objectMapper.createObjectNode()).build(); - } catch (AwsException e) { - throw remapV1Exception(e); - } catch (com.fasterxml.jackson.core.JsonProcessingException e) { - throw new AwsException("BadRequestException", e.getMessage(), 400); - } - } - - @GET - @Path("/identities/{emailIdentity}/policies") - public Response getEmailIdentityPolicies(@Context HttpHeaders headers, - @PathParam("emailIdentity") String emailIdentity) { - String region = regionResolver.resolveRegion(headers); - Map policies = sesService.getEmailIdentityPolicies(emailIdentity, region); - ObjectNode result = objectMapper.createObjectNode(); - ObjectNode policiesNode = result.putObject("Policies"); - policies.forEach(policiesNode::put); - return Response.ok(result).build(); - } - - @DELETE - @Path("/identities/{emailIdentity}/policies/{policyName}") - public Response deleteEmailIdentityPolicy(@Context HttpHeaders headers, - @PathParam("emailIdentity") String emailIdentity, - @PathParam("policyName") String policyName) { - String region = regionResolver.resolveRegion(headers); - sesService.deleteEmailIdentityPolicy(emailIdentity, policyName, region); - return Response.ok(objectMapper.createObjectNode()).build(); - } - - private String readPolicyBody(String body) throws com.fasterxml.jackson.core.JsonProcessingException { - if (body == null || body.isBlank()) { - throw new AwsException("BadRequestException", "Request body is required.", 400); - } - JsonNode request = objectMapper.readTree(body); - requireJsonObject(request); - JsonNode policyNode = request.path("Policy"); - if (policyNode.isMissingNode() || policyNode.isNull()) { - // Verified against AWS: a missing/null required member is a Smithy validation error. - throw new AwsException("BadRequestException", - "1 validation error detected: Value at 'policy' failed to satisfy constraint: " - + "Member must not be null", 400); - } - if (!policyNode.isTextual()) { - // Policy is a String; AWS rejects a non-string with an empty-bodied 400. Don't coerce - // (asText would turn 123 into "123"); surface a serialization error instead. - throw new AwsException("SerializationException", null, 400); - } - return policyNode.textValue(); - } - - // ──────────────────────── 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); - } - } - - @PUT - @Path("/identities/{emailIdentity}/dkim/signing") - public Response putEmailIdentityDkimSigningAttributes(@Context HttpHeaders headers, - @PathParam("emailIdentity") String emailIdentity, - String body) { - String region = regionResolver.resolveRegion(headers); - try { - JsonNode request = (body == null || body.isBlank()) - ? objectMapper.createObjectNode() : objectMapper.readTree(body); - requireJsonObject(request); - String origin = request.path("SigningAttributesOrigin").asText(null); - if (!"AWS_SES".equals(origin) && !"EXTERNAL".equals(origin)) { - throw new AwsException("BadRequestException", - "SigningAttributesOrigin must be AWS_SES or EXTERNAL.", 400); - } - JsonNode attrs = requireObjectOrAbsent(request, "SigningAttributes"); - String selector = attrs.path("DomainSigningSelector").asText(null); - String nextKeyLength = attrs.path("NextSigningKeyLength").asText(null); - if (nextKeyLength != null - && !"RSA_1024_BIT".equals(nextKeyLength) && !"RSA_2048_BIT".equals(nextKeyLength)) { - throw new AwsException("BadRequestException", - "NextSigningKeyLength must be RSA_1024_BIT or RSA_2048_BIT.", 400); - } - String privateKey = attrs.path("DomainSigningPrivateKey").asText(null); - if ("EXTERNAL".equals(origin) - && (selector == null || selector.isBlank() - || privateKey == null || privateKey.isBlank())) { - throw new AwsException("BadRequestException", - "EXTERNAL origin requires DomainSigningSelector and DomainSigningPrivateKey.", 400); - } - SesIdentityService.DkimSigningResult result = sesService.putDkimSigningAttributes( - emailIdentity, origin, selector, nextKeyLength, region); - ObjectNode out = objectMapper.createObjectNode(); - out.put("DkimStatus", toV2Status(result.dkimStatus())); - ArrayNode tokens = out.putArray("DkimTokens"); - result.dkimTokens().forEach(tokens::add); - return Response.ok(out).build(); - } catch (AwsException e) { - throw remapV1Exception(e); - } catch (Exception e) { - throw new AwsException("BadRequestException", e.getMessage(), 400); - } - } - - // ────────────────── Identity MAIL FROM ────────────────────────── - - @PUT - @Path("/identities/{emailIdentity}/mail-from") - public Response putEmailIdentityMailFromAttributes(@Context HttpHeaders headers, - @PathParam("emailIdentity") String emailIdentity, - String body) { - String region = regionResolver.resolveRegion(headers); - try { - if (body == null || body.isBlank()) { - throw new AwsException("BadRequestException", "Request body is required.", 400); - } - JsonNode request = objectMapper.readTree(body); - requireJsonObject(request); - JsonNode mailFromDomainNode = request.path("MailFromDomain"); - if (mailFromDomainNode.isMissingNode()) { - throw new AwsException("BadRequestException", - "MailFromDomain is required (use an empty string to clear the existing setting).", 400); - } - if (!mailFromDomainNode.isNull() && !mailFromDomainNode.isTextual()) { - throw new AwsException("BadRequestException", - "MailFromDomain must be a JSON string (or null).", 400); - } - String mailFromDomain = mailFromDomainNode.isNull() - ? "" - : mailFromDomainNode.asText(""); - JsonNode behaviorNode = request.path("BehaviorOnMxFailure"); - String behaviorV2 = null; - if (!behaviorNode.isMissingNode() && !behaviorNode.isNull()) { - if (!behaviorNode.isTextual()) { - throw new AwsException("BadRequestException", - "BehaviorOnMxFailure must be a JSON string.", 400); - } - behaviorV2 = behaviorNode.asText(null); - } - String behaviorV1 = v2BehaviorToV1(behaviorV2); - sesService.setMailFromDomain(emailIdentity, mailFromDomain, behaviorV1, region); - return Response.ok(objectMapper.createObjectNode()).build(); - } catch (AwsException e) { - throw remapV1Exception(e); - } catch (com.fasterxml.jackson.core.JsonProcessingException 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); - } - } - - // ──────────────── Identity Configuration Set ──────────────────── - - @PUT - @Path("/identities/{emailIdentity}/configuration-set") - public Response putEmailIdentityConfigurationSetAttributes(@Context HttpHeaders headers, - @PathParam("emailIdentity") String emailIdentity, - String body) { - String region = regionResolver.resolveRegion(headers); - try { - String configurationSetName = null; - if (body != null && !body.isEmpty()) { - // Only a truly empty body is "no body". A non-empty body must be a JSON object; a - // whitespace-only or otherwise unparseable body is a serialization error (verified - // against real AWS: whitespace-only returns SerializationException and does not - // clear). Within a valid object, an omitted or explicit-null ConfigurationSetName - // clears the association (as does an empty body / {}). - JsonNode request = objectMapper.readTree(body); - if (request == null || !request.isObject()) { - throw new AwsException("SerializationException", null, 400); - } - JsonNode node = request.path("ConfigurationSetName"); - if (!node.isMissingNode() && !node.isNull()) { - if (!node.isTextual()) { - throw new AwsException("BadRequestException", - "ConfigurationSetName must be a JSON string.", 400); - } - configurationSetName = node.asText(); - } - } - sesService.setEmailIdentityConfigurationSet(emailIdentity, configurationSetName, region); - return Response.ok(objectMapper.createObjectNode()).build(); - } catch (AwsException e) { - throw remapV1Exception(e); - } catch (com.fasterxml.jackson.core.JsonProcessingException e) { - throw new AwsException("SerializationException", null, 400); - } - } - // ──────────────────────────── Send Email ──────────────────────────── @POST @@ -752,103 +380,6 @@ public class SesController { // ──────────────────────────── Helpers ──────────────────────────── - private ObjectNode buildFullIdentityResponse(Identity identity, String region) { - 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, region)); - - ObjectNode mailFromAttributes = result.putObject("MailFromAttributes"); - mailFromAttributes.put("BehaviorOnMxFailure", v1BehaviorToV2(identity.getBehaviorOnMxFailure())); - String mailFromDomain = identity.getMailFromDomain(); - if (mailFromDomain != null && !mailFromDomain.isEmpty()) { - mailFromAttributes.put("MailFromDomain", mailFromDomain); - mailFromAttributes.put("MailFromDomainStatus", toV2Status(identity.getMailFromDomainStatus())); - } - - if (identity.getConfigurationSetName() != null && !identity.getConfigurationSetName().isEmpty()) { - result.put("ConfigurationSetName", identity.getConfigurationSetName()); - } - - result.putObject("Policies"); - ArrayNode tags = result.putArray("Tags"); - for (Tag t : identity.getTags()) { - ObjectNode tagNode = objectMapper.createObjectNode(); - tagNode.put("Key", t.key()); - tagNode.put("Value", t.value()); - tags.add(tagNode); - } - - return result; - } - - private static String v1BehaviorToV2(String v1) { - if ("RejectMessage".equals(v1)) { - return "REJECT_MESSAGE"; - } - return "USE_DEFAULT_VALUE"; - } - - private static String v2BehaviorToV1(String v2) { - if (v2 == null) { - return null; - } - if ("REJECT_MESSAGE".equals(v2)) { - return "RejectMessage"; - } - if ("USE_DEFAULT_VALUE".equals(v2)) { - return "UseDefaultValue"; - } - throw new AwsException("BadRequestException", - "1 validation error detected: Value at 'behaviorOnMxFailure' failed to satisfy " - + "constraint: Member must satisfy enum value set: [REJECT_MESSAGE, USE_DEFAULT_VALUE]", 400); - } - - private ObjectNode buildDkimAttributes(Identity identity, String region) { - // An email identity reports its parent domain's DKIM (SigningEnabled / Status / Tokens all - // inherit from the domain), matching AWS; a domain reports its own. - Identity src = sesService.effectiveDkimSource(identity, region); - ObjectNode dkim = objectMapper.createObjectNode(); - dkim.put("SigningEnabled", src.isDkimEnabled()); - dkim.put("Status", toV2Status(src.getDkimVerificationStatus())); - ArrayNode tokens = dkim.putArray("Tokens"); - if (src.getDkimTokens() != null) { - for (String token : src.getDkimTokens()) { - tokens.add(token); - } - } - dkim.put("SigningAttributesOrigin", src.getDkimSigningAttributesOrigin()); - dkim.put("NextSigningKeyLength", src.getDkimNextSigningKeyLength()); - dkim.put("CurrentSigningKeyLength", src.getDkimCurrentSigningKeyLength()); - if (src.getDkimLastKeyGenerationTimestamp() != null) { - // SES v2 (restJson1) serializes this timestamp as epoch seconds (a number); emitting an - // ISO string breaks the SDK's unixTimestamp unmarshaller. - dkim.put("LastKeyGenerationTimestamp", - src.getDkimLastKeyGenerationTimestamp().toEpochMilli() / 1000.0); - } - 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(); diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityController.java new file mode 100644 index 0000000000..ecd317a9fc --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityController.java @@ -0,0 +1,523 @@ +package io.github.hectorvent.floci.services.ses; + +import com.fasterxml.jackson.core.JsonProcessingException; +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 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 io.github.hectorvent.floci.services.ses.model.Tag; +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.List; +import java.util.Map; + +import static io.github.hectorvent.floci.services.ses.SesV2Json.parseTagsArray; +import static io.github.hectorvent.floci.services.ses.SesV2Json.remapV1Exception; +import static io.github.hectorvent.floci.services.ses.SesV2Json.requireJsonObject; +import static io.github.hectorvent.floci.services.ses.SesV2Json.requireObjectOrAbsent; + +/** + * SES V2 email-identity endpoints ({@code /v2/email/identities}), including the sending + * authorization policies, DKIM, MAIL FROM, feedback and default configuration set, split out of + * {@link SesController}. Reads and the single-domain attribute writes call + * {@link SesIdentityService} directly; create, delete, the policy operations and the default + * configuration set go through the {@link SesService} facade, which checks the configuration set + * exists, guards the delete against tenant associations and cascades the identity's policies. + */ +@Path("/v2/email") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class SesIdentityController { + + private static final Logger LOG = Logger.getLogger(SesIdentityController.class); + + private final SesIdentityService identityService; + private final SesService sesService; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public SesIdentityController(SesIdentityService identityService, SesService sesService, + RegionResolver regionResolver, ObjectMapper objectMapper) { + this.identityService = identityService; + this.sesService = sesService; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + @POST + @Path("/identities") + public Response createEmailIdentity(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode request = objectMapper.readTree(body); + JsonNode emailIdentityNode = request.path("EmailIdentity"); + if (!emailIdentityNode.isMissingNode() && !emailIdentityNode.isNull() + && !emailIdentityNode.isTextual()) { + // A non-string EmailIdentity is rejected rather than coerced (asText would turn 123 + // into "123"), the same as ConfigurationSetName below. + throw new AwsException("SerializationException", null, 400); + } + String emailIdentity = emailIdentityNode.asText(null); + if (emailIdentity == null || emailIdentity.isBlank()) { + throw new AwsException("BadRequestException", "EmailIdentity is required.", 400); + } + // ConfigurationSetName must be a String; AWS rejects a non-string, so reject it here too + // rather than coercing via asText (which would turn 123 into "123"). Floci surfaces this + // as a 400 SerializationException, rendered as a JSON error body by AwsExceptionMapper. + JsonNode configSetNode = request.path("ConfigurationSetName"); + String configurationSetName = null; + if (!configSetNode.isMissingNode() && !configSetNode.isNull()) { + if (!configSetNode.isTextual()) { + throw new AwsException("SerializationException", null, 400); + } + configurationSetName = configSetNode.textValue(); + } + + List parsedTags = parseTagsArray(request.path("Tags")); + + // Only the empty string means "no default configuration set" (consistent with the + // PutEmailIdentityConfigurationSetAttributes path); a whitespace-only name flows through + // name validation and is rejected as invalid input, rather than being silently ignored. + boolean hasConfigSet = configurationSetName != null && !configurationSetName.isEmpty(); + + // The service builds the complete identity (default configuration set and tags included) + // and persists it with a single write, so any failure (AlreadyExists, invalid tags, a + // missing configuration set) fails the whole call and creates nothing, matching AWS. + Identity identity = sesService.createEmailIdentity(emailIdentity, + hasConfigSet ? configurationSetName : null, parsedTags, region); + + ObjectNode result = objectMapper.createObjectNode(); + result.put("IdentityType", toV2IdentityType(identity.getIdentityType())); + result.put("VerifiedForSendingStatus", + "Success".equals(identity.getVerificationStatus())); + result.set("DkimAttributes", buildDkimAttributes(identity, region)); + + 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 = identityService.listIdentities(null, region); + + ObjectNode result = objectMapper.createObjectNode(); + ArrayNode items = result.putArray("EmailIdentities"); + for (Identity id : identities) { + // Only a not-yet-verified domain can still transition (via its DKIM records), + // so refresh just those; refreshing every identity would scan Route53 per call. + Identity current = id; + if ("Domain".equals(id.getIdentityType()) && !"Success".equals(id.getVerificationStatus())) { + Identity refreshed = + identityService.getIdentityVerificationAttributes(id.getIdentity(), region); + if (refreshed != null) { + current = refreshed; + } + } + ObjectNode item = objectMapper.createObjectNode(); + item.put("IdentityType", toV2IdentityType(current.getIdentityType())); + item.put("IdentityName", current.getIdentity()); + item.put("SendingEnabled", "Success".equals(current.getVerificationStatus())); + item.put("VerificationStatus", toV2Status(current.getVerificationStatus())); + 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 = + identityService.getIdentityVerificationAttributes(emailIdentity, region); + if (identity == null) { + throw new AwsException("NotFoundException", + "Identity " + emailIdentity + " does not exist.", 404); + } + return Response.ok(buildFullIdentityResponse(identity, region)).build(); + } + + @DELETE + @Path("/identities/{emailIdentity}") + public Response deleteEmailIdentity(@Context HttpHeaders headers, + @PathParam("emailIdentity") String emailIdentity) { + String region = regionResolver.resolveRegion(headers); + if (identityService.getIdentityVerificationAttributes(emailIdentity, region) == null) { + throw new AwsException("NotFoundException", + "Email identity " + emailIdentity + " does not exist.", 404); + } + sesService.deleteIdentity(emailIdentity, region); + LOG.infov("SES V2 DeleteEmailIdentity: {0}", emailIdentity); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + @POST + @Path("/identities/{emailIdentity}/policies/{policyName}") + public Response createEmailIdentityPolicy(@Context HttpHeaders headers, + @PathParam("emailIdentity") String emailIdentity, + @PathParam("policyName") String policyName, String body) { + String region = regionResolver.resolveRegion(headers); + try { + String policy = readPolicyBody(body); + sesService.createEmailIdentityPolicy(emailIdentity, policyName, policy, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (JsonProcessingException e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + + @PUT + @Path("/identities/{emailIdentity}/policies/{policyName}") + public Response updateEmailIdentityPolicy(@Context HttpHeaders headers, + @PathParam("emailIdentity") String emailIdentity, + @PathParam("policyName") String policyName, String body) { + String region = regionResolver.resolveRegion(headers); + try { + String policy = readPolicyBody(body); + sesService.updateEmailIdentityPolicy(emailIdentity, policyName, policy, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (JsonProcessingException e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + + @GET + @Path("/identities/{emailIdentity}/policies") + public Response getEmailIdentityPolicies(@Context HttpHeaders headers, + @PathParam("emailIdentity") String emailIdentity) { + String region = regionResolver.resolveRegion(headers); + Map policies = sesService.getEmailIdentityPolicies(emailIdentity, region); + ObjectNode result = objectMapper.createObjectNode(); + ObjectNode policiesNode = result.putObject("Policies"); + policies.forEach(policiesNode::put); + return Response.ok(result).build(); + } + + @DELETE + @Path("/identities/{emailIdentity}/policies/{policyName}") + public Response deleteEmailIdentityPolicy(@Context HttpHeaders headers, + @PathParam("emailIdentity") String emailIdentity, + @PathParam("policyName") String policyName) { + String region = regionResolver.resolveRegion(headers); + sesService.deleteEmailIdentityPolicy(emailIdentity, policyName, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private String readPolicyBody(String body) throws JsonProcessingException { + if (body == null || body.isBlank()) { + throw new AwsException("BadRequestException", "Request body is required.", 400); + } + JsonNode request = objectMapper.readTree(body); + requireJsonObject(request); + JsonNode policyNode = request.path("Policy"); + if (policyNode.isMissingNode() || policyNode.isNull()) { + // Verified against AWS: a missing/null required member is a Smithy validation error. + throw new AwsException("BadRequestException", + "1 validation error detected: Value at 'policy' failed to satisfy constraint: " + + "Member must not be null", 400); + } + if (!policyNode.isTextual()) { + // Policy is a String; AWS rejects a non-string with an empty-bodied 400. Don't coerce + // (asText would turn 123 into "123"); surface a serialization error instead. + throw new AwsException("SerializationException", null, 400); + } + return policyNode.textValue(); + } + + @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(); + identityService.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); + } + } + + @PUT + @Path("/identities/{emailIdentity}/dkim/signing") + public Response putEmailIdentityDkimSigningAttributes(@Context HttpHeaders headers, + @PathParam("emailIdentity") String emailIdentity, + String body) { + String region = regionResolver.resolveRegion(headers); + try { + JsonNode request = (body == null || body.isBlank()) + ? objectMapper.createObjectNode() : objectMapper.readTree(body); + requireJsonObject(request); + String origin = request.path("SigningAttributesOrigin").asText(null); + if (!"AWS_SES".equals(origin) && !"EXTERNAL".equals(origin)) { + throw new AwsException("BadRequestException", + "SigningAttributesOrigin must be AWS_SES or EXTERNAL.", 400); + } + JsonNode attrs = requireObjectOrAbsent(request, "SigningAttributes"); + String selector = attrs.path("DomainSigningSelector").asText(null); + String nextKeyLength = attrs.path("NextSigningKeyLength").asText(null); + if (nextKeyLength != null + && !"RSA_1024_BIT".equals(nextKeyLength) && !"RSA_2048_BIT".equals(nextKeyLength)) { + throw new AwsException("BadRequestException", + "NextSigningKeyLength must be RSA_1024_BIT or RSA_2048_BIT.", 400); + } + String privateKey = attrs.path("DomainSigningPrivateKey").asText(null); + if ("EXTERNAL".equals(origin) + && (selector == null || selector.isBlank() + || privateKey == null || privateKey.isBlank())) { + throw new AwsException("BadRequestException", + "EXTERNAL origin requires DomainSigningSelector and DomainSigningPrivateKey.", 400); + } + SesIdentityService.DkimSigningResult result = identityService.putDkimSigningAttributes( + emailIdentity, origin, selector, nextKeyLength, region); + ObjectNode out = objectMapper.createObjectNode(); + out.put("DkimStatus", toV2Status(result.dkimStatus())); + ArrayNode tokens = out.putArray("DkimTokens"); + result.dkimTokens().forEach(tokens::add); + return Response.ok(out).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (Exception e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + + @PUT + @Path("/identities/{emailIdentity}/mail-from") + public Response putEmailIdentityMailFromAttributes(@Context HttpHeaders headers, + @PathParam("emailIdentity") String emailIdentity, + String body) { + String region = regionResolver.resolveRegion(headers); + try { + if (body == null || body.isBlank()) { + throw new AwsException("BadRequestException", "Request body is required.", 400); + } + JsonNode request = objectMapper.readTree(body); + requireJsonObject(request); + JsonNode mailFromDomainNode = request.path("MailFromDomain"); + if (mailFromDomainNode.isMissingNode()) { + throw new AwsException("BadRequestException", + "MailFromDomain is required (use an empty string to clear the existing setting).", 400); + } + if (!mailFromDomainNode.isNull() && !mailFromDomainNode.isTextual()) { + throw new AwsException("BadRequestException", + "MailFromDomain must be a JSON string (or null).", 400); + } + String mailFromDomain = mailFromDomainNode.isNull() + ? "" + : mailFromDomainNode.asText(""); + JsonNode behaviorNode = request.path("BehaviorOnMxFailure"); + String behaviorV2 = null; + if (!behaviorNode.isMissingNode() && !behaviorNode.isNull()) { + if (!behaviorNode.isTextual()) { + throw new AwsException("BadRequestException", + "BehaviorOnMxFailure must be a JSON string.", 400); + } + behaviorV2 = behaviorNode.asText(null); + } + String behaviorV1 = v2BehaviorToV1(behaviorV2); + identityService.setMailFromDomain(emailIdentity, mailFromDomain, behaviorV1, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (JsonProcessingException e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + + @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(); + identityService.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); + } + } + + @PUT + @Path("/identities/{emailIdentity}/configuration-set") + public Response putEmailIdentityConfigurationSetAttributes(@Context HttpHeaders headers, + @PathParam("emailIdentity") String emailIdentity, + String body) { + String region = regionResolver.resolveRegion(headers); + try { + String configurationSetName = null; + if (body != null && !body.isEmpty()) { + // Only a truly empty body is "no body". A non-empty body must be a JSON object; a + // whitespace-only or otherwise unparseable body is a serialization error (verified + // against real AWS: whitespace-only returns SerializationException and does not + // clear). Within a valid object, an omitted or explicit-null ConfigurationSetName + // clears the association (as does an empty body / {}). + JsonNode request = objectMapper.readTree(body); + if (request == null || !request.isObject()) { + throw new AwsException("SerializationException", null, 400); + } + JsonNode node = request.path("ConfigurationSetName"); + if (!node.isMissingNode() && !node.isNull()) { + if (!node.isTextual()) { + throw new AwsException("BadRequestException", + "ConfigurationSetName must be a JSON string.", 400); + } + configurationSetName = node.asText(); + } + } + sesService.setEmailIdentityConfigurationSet(emailIdentity, configurationSetName, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } catch (AwsException e) { + throw remapV1Exception(e); + } catch (JsonProcessingException e) { + throw new AwsException("SerializationException", null, 400); + } + } + + private ObjectNode buildFullIdentityResponse(Identity identity, String region) { + 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, region)); + + ObjectNode mailFromAttributes = result.putObject("MailFromAttributes"); + mailFromAttributes.put("BehaviorOnMxFailure", v1BehaviorToV2(identity.getBehaviorOnMxFailure())); + String mailFromDomain = identity.getMailFromDomain(); + if (mailFromDomain != null && !mailFromDomain.isEmpty()) { + mailFromAttributes.put("MailFromDomain", mailFromDomain); + mailFromAttributes.put("MailFromDomainStatus", toV2Status(identity.getMailFromDomainStatus())); + } + + if (identity.getConfigurationSetName() != null && !identity.getConfigurationSetName().isEmpty()) { + result.put("ConfigurationSetName", identity.getConfigurationSetName()); + } + + result.putObject("Policies"); + ArrayNode tags = result.putArray("Tags"); + for (Tag t : identity.getTags()) { + ObjectNode tagNode = objectMapper.createObjectNode(); + tagNode.put("Key", t.key()); + tagNode.put("Value", t.value()); + tags.add(tagNode); + } + + return result; + } + + private static String v1BehaviorToV2(String v1) { + if ("RejectMessage".equals(v1)) { + return "REJECT_MESSAGE"; + } + return "USE_DEFAULT_VALUE"; + } + + private static String v2BehaviorToV1(String v2) { + if (v2 == null) { + return null; + } + if ("REJECT_MESSAGE".equals(v2)) { + return "RejectMessage"; + } + if ("USE_DEFAULT_VALUE".equals(v2)) { + return "UseDefaultValue"; + } + throw new AwsException("BadRequestException", + "1 validation error detected: Value at 'behaviorOnMxFailure' failed to satisfy " + + "constraint: Member must satisfy enum value set: [REJECT_MESSAGE, USE_DEFAULT_VALUE]", 400); + } + + private ObjectNode buildDkimAttributes(Identity identity, String region) { + // An email identity reports its parent domain's DKIM (SigningEnabled / Status / Tokens all + // inherit from the domain), matching AWS; a domain reports its own. + Identity src = identityService.effectiveDkimSource(identity, region); + ObjectNode dkim = objectMapper.createObjectNode(); + dkim.put("SigningEnabled", src.isDkimEnabled()); + dkim.put("Status", toV2Status(src.getDkimVerificationStatus())); + ArrayNode tokens = dkim.putArray("Tokens"); + if (src.getDkimTokens() != null) { + for (String token : src.getDkimTokens()) { + tokens.add(token); + } + } + dkim.put("SigningAttributesOrigin", src.getDkimSigningAttributesOrigin()); + dkim.put("NextSigningKeyLength", src.getDkimNextSigningKeyLength()); + dkim.put("CurrentSigningKeyLength", src.getDkimCurrentSigningKeyLength()); + if (src.getDkimLastKeyGenerationTimestamp() != null) { + // SES v2 (restJson1) serializes this timestamp as epoch seconds (a number); emitting an + // ISO string breaks the SDK's unixTimestamp unmarshaller. + dkim.put("LastKeyGenerationTimestamp", + src.getDkimLastKeyGenerationTimestamp().toEpochMilli() / 1000.0); + } + 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; + }; + } +} 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 ccf21f3675..aabcbedae9 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 @@ -51,6 +51,7 @@ public class SesQueryHandler { private final SesCvetService cvetService; private final SesAccountService accountService; private final SesConfigurationSetService configSetService; + private final SesPolicyService policyService; private final SesSentEmailService sentEmailService; private final ObjectMapper objectMapper; @@ -59,6 +60,7 @@ public class SesQueryHandler { SesIdentityService identityService, SesTemplateService templateService, SesCvetService cvetService, SesAccountService accountService, SesConfigurationSetService configSetService, + SesPolicyService policyService, SesSentEmailService sentEmailService, ObjectMapper objectMapper) { this.sesService = sesService; this.receiptRuleService = receiptRuleService; @@ -67,6 +69,7 @@ public class SesQueryHandler { this.cvetService = cvetService; this.accountService = accountService; this.configSetService = configSetService; + this.policyService = policyService; this.sentEmailService = sentEmailService; this.objectMapper = objectMapper; } @@ -171,19 +174,19 @@ public class SesQueryHandler { private Response handleVerifyEmailIdentity(MultivaluedMap params, String region) { String emailAddress = getParam(params, "EmailAddress"); - sesService.verifyEmailIdentity(emailAddress, region); + identityService.verifyEmailIdentity(emailAddress, region); return Response.ok(AwsQueryResponse.envelopeEmptyResult("VerifyEmailIdentity", AwsNamespaces.SES)).build(); } private Response handleVerifyEmailAddress(MultivaluedMap params, String region) { String emailAddress = getParam(params, "EmailAddress"); - sesService.verifyEmailIdentity(emailAddress, region); + identityService.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); + Identity identity = identityService.verifyDomainIdentity(domain, region); String result = new XmlBuilder().elem("VerificationToken", identity.getVerificationToken()).build(); return Response.ok(AwsQueryResponse.envelope("VerifyDomainIdentity", AwsNamespaces.SES, result)).build(); } @@ -196,7 +199,7 @@ public class SesQueryHandler { private Response handleListIdentities(MultivaluedMap params, String region) { String identityType = getParam(params, "IdentityType"); - List identities = sesService.listIdentities(identityType, region); + List identities = identityService.listIdentities(identityType, region); var xml = new XmlBuilder().start("Identities"); for (Identity id : identities) { @@ -211,7 +214,8 @@ public class SesQueryHandler { var xml = new XmlBuilder().start("VerificationAttributes"); for (String identityValue : identities) { - Identity identity = sesService.getIdentityVerificationAttributes(identityValue, region); + Identity identity = + identityService.getIdentityVerificationAttributes(identityValue, region); xml.start("entry"); xml.elem("key", identityValue); xml.start("value"); @@ -312,7 +316,7 @@ public class SesQueryHandler { } private Response handleListVerifiedEmailAddresses(String region) { - List emails = sesService.getVerifiedEmailAddresses(region); + List emails = identityService.getVerifiedEmailAddresses(region); var xml = new XmlBuilder().start("VerifiedEmailAddresses"); for (String email : emails) { xml.elem("member", email); @@ -331,7 +335,8 @@ public class SesQueryHandler { String identityValue = getParam(params, "Identity"); String notificationType = getParam(params, "NotificationType"); String snsTopic = getParam(params, "SnsTopic"); - sesService.setIdentityNotificationTopic(identityValue, notificationType, snsTopic, region); + identityService.setIdentityNotificationTopic(identityValue, notificationType, snsTopic, + region); return Response.ok(AwsQueryResponse.envelopeEmptyResult("SetIdentityNotificationTopic", AwsNamespaces.SES)).build(); } @@ -340,7 +345,8 @@ public class SesQueryHandler { var xml = new XmlBuilder().start("NotificationAttributes"); for (String identityValue : identities) { - Identity identity = sesService.getIdentityNotificationAttributes(identityValue, region); + Identity identity = + identityService.getIdentityNotificationAttributes(identityValue, region); if (identity == null) { continue; } @@ -369,9 +375,10 @@ public class SesQueryHandler { var xml = new XmlBuilder().start("DkimAttributes"); for (String identityValue : identities) { - Identity identity = sesService.getIdentityVerificationAttributes(identityValue, region); + Identity identity = + identityService.getIdentityVerificationAttributes(identityValue, region); // An email identity reports its parent domain's DKIM state (matching AWS). - Identity src = sesService.effectiveDkimSource(identity, region); + Identity src = identityService.effectiveDkimSource(identity, region); xml.start("entry"); xml.elem("key", identityValue); xml.start("value"); @@ -394,20 +401,20 @@ public class SesQueryHandler { private Response handleSetIdentityFeedbackForwardingEnabled(MultivaluedMap params, String region) { String identityValue = getParam(params, "Identity"); boolean enabled = parseXsdBoolean(params, "ForwardingEnabled"); - sesService.setFeedbackForwardingEnabled(identityValue, enabled, region); + identityService.setFeedbackForwardingEnabled(identityValue, enabled, region); return Response.ok(AwsQueryResponse.envelopeEmptyResult("SetIdentityFeedbackForwardingEnabled", AwsNamespaces.SES)).build(); } private Response handleSetIdentityDkimEnabled(MultivaluedMap params, String region) { String identityValue = getParam(params, "Identity"); boolean enabled = parseXsdBoolean(params, "DkimEnabled"); - sesService.setDkimAttributes(identityValue, enabled, region); + identityService.setDkimAttributes(identityValue, enabled, region); return Response.ok(AwsQueryResponse.envelopeEmptyResult("SetIdentityDkimEnabled", AwsNamespaces.SES)).build(); } private Response handleVerifyDomainDkim(MultivaluedMap params, String region) { String domain = getParam(params, "Domain"); - List tokens = sesService.verifyDomainDkim(domain, region); + List tokens = identityService.verifyDomainDkim(domain, region); var xml = new XmlBuilder().start("DkimTokens"); for (String token : tokens) { xml.elem("member", token); @@ -420,7 +427,8 @@ public class SesQueryHandler { String identityValue = getParam(params, "Identity"); String notificationType = getParam(params, "NotificationType"); boolean enabled = parseXsdBoolean(params, "Enabled"); - sesService.setHeadersInNotificationsEnabled(identityValue, notificationType, enabled, region); + identityService.setHeadersInNotificationsEnabled(identityValue, notificationType, enabled, + region); return Response.ok(AwsQueryResponse.envelopeEmptyResult("SetIdentityHeadersInNotificationsEnabled", AwsNamespaces.SES)).build(); } @@ -432,7 +440,8 @@ public class SesQueryHandler { "MailFromDomain is required (use an empty string to clear the existing setting).", 400); } String behaviorOnMxFailure = getParam(params, "BehaviorOnMXFailure"); - sesService.setMailFromDomain(identityValue, mailFromDomain, behaviorOnMxFailure, region); + identityService.setMailFromDomain(identityValue, mailFromDomain, behaviorOnMxFailure, + region); return Response.ok(AwsQueryResponse.envelopeEmptyResult("SetIdentityMailFromDomain", AwsNamespaces.SES)).build(); } @@ -462,7 +471,7 @@ public class SesQueryHandler { List identities = extractMembers(params, "Identities"); var xml = new XmlBuilder().start("MailFromDomainAttributes"); for (String identityValue : identities) { - Identity identity = sesService.getMailFromAttributes(identityValue, region); + Identity identity = identityService.getMailFromAttributes(identityValue, region); xml.start("entry"); xml.elem("key", identityValue); xml.start("value"); @@ -485,14 +494,14 @@ public class SesQueryHandler { String identity = requireParam(params, "Identity"); String policyName = requireParam(params, "PolicyName"); String policy = requireParam(params, "Policy"); - sesService.putIdentityPolicy(identity, policyName, policy, region); + policyService.putIdentityPolicy(identity, policyName, policy, region); return Response.ok(AwsQueryResponse.envelopeEmptyResult("PutIdentityPolicy", AwsNamespaces.SES)).build(); } private Response handleGetIdentityPolicies(MultivaluedMap params, String region) { String identity = requireParam(params, "Identity"); List names = extractMembers(params, "PolicyNames"); - Map policies = sesService.getIdentityPolicies(identity, names, region); + Map policies = policyService.getIdentityPolicies(identity, names, region); var xml = new XmlBuilder().start("Policies"); policies.forEach((name, doc) -> xml.start("entry").elem("key", name).elem("value", doc).end("entry")); xml.end("Policies"); @@ -502,7 +511,7 @@ public class SesQueryHandler { private Response handleListIdentityPolicies(MultivaluedMap params, String region) { String identity = requireParam(params, "Identity"); var xml = new XmlBuilder().start("PolicyNames"); - for (String name : sesService.listIdentityPolicyNames(identity, region)) { + for (String name : policyService.listIdentityPolicyNames(identity, region)) { xml.elem("member", name); } xml.end("PolicyNames"); @@ -512,7 +521,7 @@ public class SesQueryHandler { private Response handleDeleteIdentityPolicy(MultivaluedMap params, String region) { String identity = requireParam(params, "Identity"); String policyName = requireParam(params, "PolicyName"); - sesService.deleteIdentityPolicy(identity, policyName, region); + policyService.deleteIdentityPolicy(identity, policyName, region); return Response.ok(AwsQueryResponse.envelopeEmptyResult("DeleteIdentityPolicy", AwsNamespaces.SES)).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 dd1ca99f4f..eb1a417b48 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 @@ -55,9 +55,11 @@ public class SesService { private static final int MAX_BULK_DESTINATIONS = 50; private static final int MAX_RECIPIENTS_PER_DESTINATION = 50; - // Identities extracted to SesIdentityService (CRUD, verification, MAIL FROM, notifications, - // tags, and the DKIM state machine with its Route53 lookup). The facade keeps the cross-domain - // flows and send-path reads, reaching the store through its find/save. + // Identities live in SesIdentityService (CRUD, verification, MAIL FROM, notifications, tags, + // and the DKIM state machine with its Route53 lookup), which the v2 controller and the v1 + // handler call directly. The facade keeps the cross-domain flows (create's configuration-set + // check, the tenant-guarded delete with its policy cascade, the default configuration set) and + // the send-path reads, reaching the store through its find/save. private final SesIdentityService identityService; // Sent-email records extracted to SesSentEmailService. The send path records finished emails via // it; the account and v1 statistics reads go to the service directly, inspection still reads @@ -82,8 +84,9 @@ public class SesService { // and the unsubscribe endpoint call directly; the facade only reaches it from the send-path // list-management orchestration and the ARN-dispatched tagging. private final SesContactService contactService; - // Identity (sending authorization) policy storage, extracted to SesPolicyService. - // The facade keeps the identity-existence check and delegates the rest. + // Identity (sending authorization) policy storage lives in SesPolicyService, which the v1 + // handler calls directly; the facade keeps the v2 operations, which check the identity exists + // first, and the delete cascade. private final SesPolicyService policyService; // Custom verification email templates: storage extracted to SesCvetService, which the v2 // controller and the v1 handler call directly for get/list/delete. The facade keeps create and @@ -157,10 +160,6 @@ public class SesService { this.regionResolver = null; } - public Identity verifyEmailIdentity(String emailAddress, String region) { - return identityService.verifyEmailIdentity(emailAddress, region); - } - /** * v2 CreateEmailIdentity. The identity domain builds and persists the complete record in one * write; only the configuration-set existence check is cross-domain, so it is passed in as the @@ -174,10 +173,6 @@ public class SesService { configurationSetExistsCheck); } - public Identity verifyDomainIdentity(String domain, String region) { - return identityService.verifyDomainIdentity(domain, region); - } - public void deleteIdentity(String identityValue, String region) { if (identityValue == null || identityValue.isBlank()) { return; @@ -196,14 +191,6 @@ public class SesService { LOG.infov("Deleted identity: {0}", identityValue); } - public List listIdentities(String identityType, String region) { - return identityService.listIdentities(identityType, region); - } - - public Identity getIdentityVerificationAttributes(String identityValue, String region) { - return identityService.getIdentityVerificationAttributes(identityValue, region); - } - public String sendEmail(String source, List toAddresses, List ccAddresses, List bccAddresses, List replyToAddresses, String returnPath, String subject, String bodyText, String bodyHtml, @@ -540,38 +527,6 @@ public class SesService { return events; } - public void setIdentityNotificationTopic(String identityValue, String notificationType, - String snsTopic, String region) { - identityService.setIdentityNotificationTopic(identityValue, notificationType, snsTopic, region); - } - - public Identity getIdentityNotificationAttributes(String identityValue, String region) { - return identityService.getIdentityNotificationAttributes(identityValue, region); - } - - public void setDkimAttributes(String identityValue, boolean signingEnabled, String region) { - identityService.setDkimAttributes(identityValue, signingEnabled, region); - } - - public List verifyDomainDkim(String domain, String region) { - return identityService.verifyDomainDkim(domain, region); - } - - public SesIdentityService.DkimSigningResult putDkimSigningAttributes(String identityValue, String origin, - String signingSelector, String nextKeyLength, - String region) { - return identityService.putDkimSigningAttributes(identityValue, origin, signingSelector, - nextKeyLength, region); - } - - public Identity effectiveDkimSource(Identity identity, String region) { - return identityService.effectiveDkimSource(identity, region); - } - - public void setFeedbackForwardingEnabled(String identityValue, boolean enabled, String region) { - identityService.setFeedbackForwardingEnabled(identityValue, enabled, region); - } - public void setEmailIdentityConfigurationSet(String identityValue, String configurationSetName, String region) { Identity identity = identityService.find(identityValue, region) @@ -638,24 +593,6 @@ public class SesService { return cs; } - public void setMailFromDomain(String identityValue, String mailFromDomain, - String behaviorOnMxFailure, String region) { - identityService.setMailFromDomain(identityValue, mailFromDomain, behaviorOnMxFailure, region); - } - - public Identity getMailFromAttributes(String identityValue, String region) { - return identityService.getMailFromAttributes(identityValue, region); - } - - public void setHeadersInNotificationsEnabled(String identityValue, String notificationType, - boolean enabled, String region) { - identityService.setHeadersInNotificationsEnabled(identityValue, notificationType, enabled, region); - } - - public List getVerifiedEmailAddresses(String region) { - return identityService.getVerifiedEmailAddresses(region); - } - public List getEmails() { return sentEmailService.listAll(); } @@ -854,7 +791,7 @@ public class SesService { } private boolean isVerifiedDomainIdentity(String domain, String region) { - Identity identity = getIdentityVerificationAttributes(domain, region); + Identity identity = identityService.getIdentityVerificationAttributes(domain, region); return identity != null && "Success".equals(identity.getVerificationStatus()) && "Domain".equals(identity.getIdentityType()); } @@ -1053,10 +990,6 @@ public class SesService { // Policy storage lives in SesPolicyService; this facade forwards, and for the v2 mutators it runs // the identity-existence check (an Identity-domain read) first, before delegating. - public void putIdentityPolicy(String identity, String policyName, String policy, String region) { - policyService.putIdentityPolicy(identity, policyName, policy, region); - } - public void createEmailIdentityPolicy(String identity, String policyName, String policy, String region) { requireIdentityExists(identity, region); policyService.createEmailIdentityPolicy(identity, policyName, policy, region); @@ -1072,23 +1005,11 @@ public class SesService { return policyService.listAllPolicies(identity, region); } - public Map getIdentityPolicies(String identity, List policyNames, String region) { - return policyService.getIdentityPolicies(identity, policyNames, region); - } - - public List listIdentityPolicyNames(String identity, String region) { - return policyService.listIdentityPolicyNames(identity, region); - } - public void deleteEmailIdentityPolicy(String identity, String policyName, String region) { requireIdentityExists(identity, region); policyService.deleteEmailIdentityPolicy(identity, policyName, region); } - public void deleteIdentityPolicy(String identity, String policyName, String region) { - policyService.deleteIdentityPolicy(identity, policyName, region); - } - private void requireIdentityExists(String identity, String region) { if (identityService.find(identity, region).isEmpty()) { throw new AwsException("NotFoundException", diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java index 5c2485de1a..e420b3a6de 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java @@ -26,7 +26,7 @@ class SesServiceDkimLookupCacheTest { private static final String REGION = "us-east-1"; private static final String DOMAIN = "example.com"; - private SesService service; + private SesIdentityService identities; private InMemoryStorage identityStore; private Route53Service route53Service; private MutableClock clock; @@ -40,7 +40,8 @@ class SesServiceDkimLookupCacheTest { .route53Service(route53Service) .clock(clock); identityStore = builder.identityStore(); - service = builder.build(); + builder.build(); + identities = builder.identityService(); } @Test @@ -48,8 +49,12 @@ class SesServiceDkimLookupCacheTest { Identity identity = storePendingDomainIdentity(); stubRoute53(identity, List.of()); - assertEquals("Pending", service.getIdentityVerificationAttributes(DOMAIN, REGION).getVerificationStatus()); - assertEquals("Pending", service.getIdentityVerificationAttributes(DOMAIN, REGION).getVerificationStatus()); + assertEquals("Pending", + identities.getIdentityVerificationAttributes(DOMAIN, REGION) + .getVerificationStatus()); + assertEquals("Pending", + identities.getIdentityVerificationAttributes(DOMAIN, REGION) + .getVerificationStatus()); verify(route53Service, times(1)).listHostedZones(null, Integer.MAX_VALUE); verify(route53Service, times(1)).listResourceRecordSets(eq("zone-1"), eq(null), eq(null), eq(Integer.MAX_VALUE)); @@ -60,9 +65,13 @@ class SesServiceDkimLookupCacheTest { Identity identity = storePendingDomainIdentity(); stubRoute53(identity, List.of()); - assertEquals("Pending", service.getIdentityVerificationAttributes(DOMAIN, REGION).getVerificationStatus()); + assertEquals("Pending", + identities.getIdentityVerificationAttributes(DOMAIN, REGION) + .getVerificationStatus()); clock.advance(Duration.ofSeconds(5)); - assertEquals("Pending", service.getIdentityVerificationAttributes(DOMAIN, REGION).getVerificationStatus()); + assertEquals("Pending", + identities.getIdentityVerificationAttributes(DOMAIN, REGION) + .getVerificationStatus()); verify(route53Service, times(2)).listHostedZones(null, Integer.MAX_VALUE); verify(route53Service, times(2)).listResourceRecordSets(eq("zone-1"), eq(null), eq(null), eq(Integer.MAX_VALUE)); @@ -74,14 +83,20 @@ class SesServiceDkimLookupCacheTest { List matchingRecords = buildMatchingRecords(identity); stubRoute53(identity, List.of()); - assertEquals("Pending", service.getIdentityVerificationAttributes(DOMAIN, REGION).getVerificationStatus()); + assertEquals("Pending", + identities.getIdentityVerificationAttributes(DOMAIN, REGION) + .getVerificationStatus()); when(route53Service.listResourceRecordSets("zone-1", null, null, Integer.MAX_VALUE)) .thenReturn(matchingRecords); clock.advance(Duration.ofSeconds(5)); - assertEquals("Success", service.getIdentityVerificationAttributes(DOMAIN, REGION).getVerificationStatus()); - assertEquals("Success", service.getIdentityVerificationAttributes(DOMAIN, REGION).getVerificationStatus()); + assertEquals("Success", + identities.getIdentityVerificationAttributes(DOMAIN, REGION) + .getVerificationStatus()); + assertEquals("Success", + identities.getIdentityVerificationAttributes(DOMAIN, REGION) + .getVerificationStatus()); verify(route53Service, times(4)).listHostedZones(null, Integer.MAX_VALUE); verify(route53Service, times(4)).listResourceRecordSets(eq("zone-1"), eq(null), eq(null), eq(Integer.MAX_VALUE)); diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java index a3704f5505..0f455c4f2e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java @@ -18,14 +18,15 @@ class SesServiceLegacyDkimTokensTest { private static final String REGION = "us-east-1"; - private SesService service; + private SesIdentityService identities; private InMemoryStorage identityStore; @BeforeEach void setUp() { SesServiceTestBuilder builder = SesServiceTestBuilder.create(); identityStore = builder.identityStore(); - service = builder.build(); + builder.build(); + identities = builder.identityService(); } @Test @@ -40,7 +41,8 @@ class SesServiceLegacyDkimTokensTest { String key = "identity::" + REGION + "::" + legacy.getIdentity(); identityStore.put(key, legacy); - Identity refreshed = service.getIdentityVerificationAttributes(legacy.getIdentity(), REGION); + Identity refreshed = + identities.getIdentityVerificationAttributes(legacy.getIdentity(), REGION); assertSame(legacy, refreshed); assertNotNull(refreshed.getDkimTokens()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.java index 799104d80d..af07cc726e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceTestBuilder.java @@ -52,11 +52,12 @@ final class SesServiceTestBuilder { private Route53Service route53Service = null; private ObjectMapper objectMapper = new ObjectMapper(); private Clock clock = Clock.systemUTC(); - // Built by build(); exposed so tests can seed contacts, account suppression and configuration-set - // options through the domain services now that the facade no longer forwards those operations. + // Built by build(); exposed so tests can reach the domain services directly now that the facade + // no longer forwards their operations. private SesContactService contactService; private SesSuppressionService suppressionService; private SesConfigurationSetService configSetService; + private SesIdentityService identityService; static SesServiceTestBuilder create() { return new SesServiceTestBuilder(); @@ -133,13 +134,21 @@ final class SesServiceTestBuilder { return configSetService; } + SesIdentityService identityService() { + if (identityService == null) { + throw new IllegalStateException("call build() first"); + } + return identityService; + } + SesService build() { contactService = new SesContactService(contactListStore, contactStore, clock); suppressionService = new SesSuppressionService(suppressionStore, accountSuppressionStore, new InMemoryStorage<>()); configSetService = new SesConfigurationSetService(configSetStore); + identityService = new SesIdentityService(identityStore, route53Service, clock); return new SesService( - new SesIdentityService(identityStore, route53Service, clock), + identityService, new SesSentEmailService(emailStore), new SesTemplateService(templateStore, objectMapper, new SecureRandom()), configSetService,