mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
feat(ses): implement email template CRUD with stored, inline, and ARN variants (#573)
* feat(ses): implement email template CRUD with stored, inline, and ARN variants
Adds CreateTemplate / GetTemplate / UpdateTemplate /
DeleteTemplate / ListTemplates on both V2 REST JSON
(/v2/email/templates) and V1 Query.
SendEmail / SendTemplatedEmail resolve templates in three forms
with Mustache-style {{var}} substitution against TemplateData:
- TemplateName references a stored template
- TemplateArn extracts the name from the template/<name>
segment of an SES template ARN (region and account segments
are not validated, mirroring how KMS / Secrets Manager
handle ARNs in Floci)
- TemplateContent (V2 only) supplies inline subject / text /
html without storing the template first
V2 Content.Template requires exactly one of TemplateName,
TemplateArn, or TemplateContent; violations return
BadRequestException (400). V1 SendTemplatedEmail accepts
TemplateArn either alone or alongside Template (name) — the
name is used for resolution when both are present, matching
AWS where boto3 and the Java SDK keep Template as a required
field and treat TemplateArn as supplementary for cross-account
addressing.
Templates persist region-scoped via StorageFactory in
ses-templates.json. Template names reject leading/trailing
whitespace (same rule as identities) and are validated through
a single validateTemplateName helper reachable from every
resolution path. listTemplates is sorted by CreatedTimestamp
with TemplateName as a tiebreaker for deterministic output.
Error codes: the service layer throws V1-style codes
(TemplateDoesNotExist / AlreadyExists / InvalidTemplate /
InvalidParameterValue); SesController remaps them to
NotFoundException (404) / AlreadyExistsException (400) /
BadRequestException (400) for V2 callers.
* test(ses): add Python and Java SDK compatibility tests for templates
Covers boto3 (ses / sesv2) and AWS Java SDK v2 (SesClient /
SesV2Client) against the SES email template CRUD, inline
TemplateContent, and TemplateArn paths. Happy path,
duplicate-create rejection, missing-template lookups,
Mustache-style variable substitution, and 3-way selector
conflicts on V2 Content.Template are exercised on both SDK
surfaces.
Adds:
- Python: ses_client / sesv2_client conftest fixtures and a
tests/test_ses_templates.py suite covering V1 + V2
- Java: sesv2 Maven dependency, SesV2Client factory in
TestFixtures, and a SesTemplateTest covering V1 + V2
* docs(ses): document email template CRUD and templated send
Adds the new V1 template actions (CreateTemplate / GetTemplate
/ UpdateTemplate / DeleteTemplate / ListTemplates /
SendTemplatedEmail) and the V2 /v2/email/templates endpoints
to the SES service reference, and extends the README service
matrix to mention template support on the SES / SES v2 rows.
* fix(ses): add template actions to SES_ACTIONS for unsigned request routing
Unsigned clients (curl, aws --no-sign-request) were falling through to
the SQS handler because the six template Query actions were not
registered in SES_ACTIONS.
* fix(ses): narrow exception catch to JsonProcessingException in template endpoints
Broad Exception catch was masking unexpected errors (e.g. NPE) as 400
responses. Narrowed to JsonProcessingException which is the only
checked exception from objectMapper.readTree().
* test(ses): add template variable substitution edge cases and cross-region isolation
Add SesServiceTemplateTest with 14 unit tests for applyTemplateData
covering undefined variables, spaced/hyphenated names, unclosed braces,
non-string JSON values, regex metacharacters, and case sensitivity.
Add cross-region isolation integration test verifying templates created
in one region are not visible in another.
* test(ses): add awscli compatibility tests for template CRUD and templated send
Cover create, get, update, list, delete template and send-templated-email
via the AWS CLI. Uses JSON parameter format to avoid awscli parser issues
with Mustache-style {{variable}} syntax.
---------
Co-authored-by: Kenshin OKINAKA <kenshin_okinaka@realcross.co.jp>
This commit is contained in:
1 parent
e0dc45e012
commit
763ea379d7
18 files changed
+2583
-14
No files matched your search
@@ -257,7 +257,9 @@ public class AwsQueryController {
|
||||
"SendEmail", "SendRawEmail", "GetSendQuota", "GetSendStatistics",
|
||||
"GetAccountSendingEnabled", "ListVerifiedEmailAddresses", "DeleteVerifiedEmailAddress",
|
||||
"SetIdentityNotificationTopic", "GetIdentityNotificationAttributes",
|
||||
"GetIdentityDkimAttributes"
|
||||
"GetIdentityDkimAttributes",
|
||||
"CreateTemplate", "UpdateTemplate", "GetTemplate", "DeleteTemplate",
|
||||
"ListTemplates", "SendTemplatedEmail"
|
||||
);
|
||||
|
||||
private static final Set<String> COGNITO_ACTIONS = Set.of(
|
||||
|
||||
@@ -2,6 +2,7 @@ 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.EmailTemplate;
|
||||
import io.github.hectorvent.floci.services.ses.model.Identity;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -226,10 +227,38 @@ public class SesController {
|
||||
messageId = sesService.sendEmail(fromEmailAddress, toAddresses, ccAddresses,
|
||||
bccAddresses, replyToAddresses, 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, replyToAddresses, subject, templateData, null, region);
|
||||
JsonNode template = content.path("Template");
|
||||
String templateName = template.path("TemplateName").asText(null);
|
||||
String templateArn = template.path("TemplateArn").asText(null);
|
||||
boolean hasName = templateName != null && !templateName.isBlank();
|
||||
boolean hasArn = templateArn != null && !templateArn.isBlank();
|
||||
boolean hasInline = template.has("TemplateContent");
|
||||
int selectorCount = (hasName ? 1 : 0) + (hasArn ? 1 : 0) + (hasInline ? 1 : 0);
|
||||
if (selectorCount > 1) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Content.Template must specify exactly one of TemplateName, TemplateArn, or TemplateContent.",
|
||||
400);
|
||||
}
|
||||
if (selectorCount == 0) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Content.Template requires TemplateName, TemplateArn, or TemplateContent.", 400);
|
||||
}
|
||||
JsonNode templateData = parseTemplateData(template.path("TemplateData").asText(""));
|
||||
if (hasName || hasArn) {
|
||||
String resolvedName = hasName
|
||||
? templateName
|
||||
: SesService.templateNameFromArn(templateArn);
|
||||
messageId = sesService.sendTemplatedEmail(fromEmailAddress, toAddresses, ccAddresses,
|
||||
bccAddresses, replyToAddresses, resolvedName, templateData, region);
|
||||
} else {
|
||||
JsonNode inline = template.path("TemplateContent");
|
||||
String subject = inline.path("Subject").asText(null);
|
||||
String text = inline.path("Text").asText(null);
|
||||
String html = inline.path("Html").asText(null);
|
||||
messageId = sesService.sendInlineTemplatedEmail(fromEmailAddress, toAddresses,
|
||||
ccAddresses, bccAddresses, replyToAddresses,
|
||||
subject, text, html, templateData, region);
|
||||
}
|
||||
} else {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Content must contain Raw, Simple, or Template.", 400);
|
||||
@@ -248,6 +277,93 @@ public class SesController {
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── Templates ────────────────────────────
|
||||
|
||||
@POST
|
||||
@Path("/templates")
|
||||
public Response createEmailTemplate(@Context HttpHeaders headers, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
JsonNode request = objectMapper.readTree(body);
|
||||
String templateName = request.path("TemplateName").asText(null);
|
||||
if (templateName == null || templateName.isBlank()) {
|
||||
throw new AwsException("BadRequestException", "TemplateName is required.", 400);
|
||||
}
|
||||
EmailTemplate template = parseTemplateContent(templateName, request.path("TemplateContent"));
|
||||
sesService.createTemplate(template, region);
|
||||
LOG.infov("SES V2 CreateEmailTemplate: {0}", templateName);
|
||||
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("/templates")
|
||||
public Response listEmailTemplates(@Context HttpHeaders headers) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
List<EmailTemplate> templates = sesService.listTemplates(region);
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
ArrayNode items = result.putArray("TemplatesMetadata");
|
||||
for (EmailTemplate t : templates) {
|
||||
ObjectNode item = objectMapper.createObjectNode();
|
||||
item.put("TemplateName", t.getTemplateName());
|
||||
if (t.getCreatedTimestamp() != null) {
|
||||
item.put("CreatedTimestamp", t.getCreatedTimestamp().getEpochSecond());
|
||||
}
|
||||
items.add(item);
|
||||
}
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/templates/{templateName}")
|
||||
public Response getEmailTemplate(@Context HttpHeaders headers,
|
||||
@PathParam("templateName") String templateName) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
EmailTemplate template = sesService.getTemplate(templateName, region);
|
||||
return Response.ok(buildTemplateResponse(template)).build();
|
||||
} catch (AwsException e) {
|
||||
throw remapV1Exception(e);
|
||||
}
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/templates/{templateName}")
|
||||
public Response updateEmailTemplate(@Context HttpHeaders headers,
|
||||
@PathParam("templateName") String templateName,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
JsonNode request = objectMapper.readTree(body);
|
||||
EmailTemplate template = parseTemplateContent(templateName, request.path("TemplateContent"));
|
||||
sesService.updateTemplate(template, region);
|
||||
LOG.infov("SES V2 UpdateEmailTemplate: {0}", templateName);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/templates/{templateName}")
|
||||
public Response deleteEmailTemplate(@Context HttpHeaders headers,
|
||||
@PathParam("templateName") String templateName) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
sesService.deleteTemplate(templateName, region);
|
||||
LOG.infov("SES V2 DeleteEmailTemplate: {0}", templateName);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
} catch (AwsException e) {
|
||||
throw remapV1Exception(e);
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── Account ────────────────────────────
|
||||
|
||||
@GET
|
||||
@@ -354,10 +470,50 @@ public class SesController {
|
||||
return all;
|
||||
}
|
||||
|
||||
private static AwsException remapV1Exception(AwsException e) {
|
||||
if ("InvalidParameterValue".equals(e.getErrorCode())) {
|
||||
return new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
private EmailTemplate parseTemplateContent(String templateName, JsonNode content) {
|
||||
String subject = content.path("Subject").asText(null);
|
||||
String text = content.path("Text").asText(null);
|
||||
String html = content.path("Html").asText(null);
|
||||
return new EmailTemplate(templateName, subject, text, html);
|
||||
}
|
||||
|
||||
private ObjectNode buildTemplateResponse(EmailTemplate template) {
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
result.put("TemplateName", template.getTemplateName());
|
||||
ObjectNode content = result.putObject("TemplateContent");
|
||||
if (template.getSubject() != null) {
|
||||
content.put("Subject", template.getSubject());
|
||||
}
|
||||
return e;
|
||||
if (template.getTextPart() != null) {
|
||||
content.put("Text", template.getTextPart());
|
||||
}
|
||||
if (template.getHtmlPart() != null) {
|
||||
content.put("Html", template.getHtmlPart());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private JsonNode parseTemplateData(String raw) {
|
||||
if (raw == null || raw.isBlank()) {
|
||||
return objectMapper.createObjectNode();
|
||||
}
|
||||
try {
|
||||
return objectMapper.readTree(raw);
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Invalid TemplateData JSON: " + e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException remapV1Exception(AwsException e) {
|
||||
return switch (e.getErrorCode()) {
|
||||
case "InvalidParameterValue", "InvalidTemplate" ->
|
||||
new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
case "TemplateDoesNotExist" ->
|
||||
new AwsException("NotFoundException", e.getMessage(), 404);
|
||||
case "AlreadyExists" ->
|
||||
new AwsException("AlreadyExistsException", e.getMessage(), 400);
|
||||
default -> e;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,10 @@ import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsNamespaces;
|
||||
import io.github.hectorvent.floci.core.common.AwsQueryResponse;
|
||||
import io.github.hectorvent.floci.core.common.XmlBuilder;
|
||||
import io.github.hectorvent.floci.services.ses.model.EmailTemplate;
|
||||
import io.github.hectorvent.floci.services.ses.model.Identity;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
@@ -24,10 +27,12 @@ public class SesQueryHandler {
|
||||
private static final Logger LOG = Logger.getLogger(SesQueryHandler.class);
|
||||
|
||||
private final SesService sesService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public SesQueryHandler(SesService sesService) {
|
||||
public SesQueryHandler(SesService sesService, ObjectMapper objectMapper) {
|
||||
this.sesService = sesService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public Response handle(String action, MultivaluedMap<String, String> params, String region) {
|
||||
@@ -51,6 +56,12 @@ public class SesQueryHandler {
|
||||
case "SetIdentityNotificationTopic" -> handleSetIdentityNotificationTopic(params, region);
|
||||
case "GetIdentityNotificationAttributes" -> handleGetIdentityNotificationAttributes(params, region);
|
||||
case "GetIdentityDkimAttributes" -> handleGetIdentityDkimAttributes(params, region);
|
||||
case "CreateTemplate" -> handleCreateTemplate(params, region);
|
||||
case "UpdateTemplate" -> handleUpdateTemplate(params, region);
|
||||
case "GetTemplate" -> handleGetTemplate(params, region);
|
||||
case "DeleteTemplate" -> handleDeleteTemplate(params, region);
|
||||
case "ListTemplates" -> handleListTemplates(region);
|
||||
case "SendTemplatedEmail" -> handleSendTemplatedEmail(params, region);
|
||||
default -> AwsQueryResponse.error("UnsupportedOperation",
|
||||
"Operation " + action + " is not supported by SES.", AwsNamespaces.SES, 400);
|
||||
};
|
||||
@@ -246,6 +257,105 @@ public class SesQueryHandler {
|
||||
return Response.ok(AwsQueryResponse.envelope("GetIdentityDkimAttributes", AwsNamespaces.SES, xml.build())).build();
|
||||
}
|
||||
|
||||
// --- Templates ---
|
||||
|
||||
private Response handleCreateTemplate(MultivaluedMap<String, String> params, String region) {
|
||||
EmailTemplate template = readTemplateParams(params);
|
||||
sesService.createTemplate(template, region);
|
||||
return Response.ok(AwsQueryResponse.envelopeEmptyResult("CreateTemplate", AwsNamespaces.SES)).build();
|
||||
}
|
||||
|
||||
private Response handleUpdateTemplate(MultivaluedMap<String, String> params, String region) {
|
||||
EmailTemplate template = readTemplateParams(params);
|
||||
sesService.updateTemplate(template, region);
|
||||
return Response.ok(AwsQueryResponse.envelopeEmptyResult("UpdateTemplate", AwsNamespaces.SES)).build();
|
||||
}
|
||||
|
||||
private Response handleGetTemplate(MultivaluedMap<String, String> params, String region) {
|
||||
String templateName = getParam(params, "TemplateName");
|
||||
EmailTemplate template = sesService.getTemplate(templateName, region);
|
||||
var xml = new XmlBuilder().start("Template")
|
||||
.elem("TemplateName", template.getTemplateName());
|
||||
if (template.getSubject() != null) {
|
||||
xml.elem("SubjectPart", template.getSubject());
|
||||
}
|
||||
if (template.getTextPart() != null) {
|
||||
xml.elem("TextPart", template.getTextPart());
|
||||
}
|
||||
if (template.getHtmlPart() != null) {
|
||||
xml.elem("HtmlPart", template.getHtmlPart());
|
||||
}
|
||||
xml.end("Template");
|
||||
return Response.ok(AwsQueryResponse.envelope("GetTemplate", AwsNamespaces.SES, xml.build())).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteTemplate(MultivaluedMap<String, String> params, String region) {
|
||||
String templateName = getParam(params, "TemplateName");
|
||||
sesService.deleteTemplate(templateName, region);
|
||||
return Response.ok(AwsQueryResponse.envelopeEmptyResult("DeleteTemplate", AwsNamespaces.SES)).build();
|
||||
}
|
||||
|
||||
private Response handleListTemplates(String region) {
|
||||
List<EmailTemplate> templates = sesService.listTemplates(region);
|
||||
var xml = new XmlBuilder().start("TemplatesMetadata");
|
||||
for (EmailTemplate t : templates) {
|
||||
xml.start("member")
|
||||
.elem("Name", t.getTemplateName());
|
||||
if (t.getCreatedTimestamp() != null) {
|
||||
xml.elem("CreatedTimestamp", t.getCreatedTimestamp().toString());
|
||||
}
|
||||
xml.end("member");
|
||||
}
|
||||
xml.end("TemplatesMetadata");
|
||||
return Response.ok(AwsQueryResponse.envelope("ListTemplates", AwsNamespaces.SES, xml.build())).build();
|
||||
}
|
||||
|
||||
private Response handleSendTemplatedEmail(MultivaluedMap<String, String> params, String region) {
|
||||
String source = getParam(params, "Source");
|
||||
List<String> toAddresses = extractMembers(params, "Destination.ToAddresses");
|
||||
List<String> ccAddresses = extractMembers(params, "Destination.CcAddresses");
|
||||
List<String> bccAddresses = extractMembers(params, "Destination.BccAddresses");
|
||||
List<String> replyToAddresses = extractMembers(params, "ReplyToAddresses");
|
||||
String templateName = getParam(params, "Template");
|
||||
String templateArn = getParam(params, "TemplateArn");
|
||||
String templateDataRaw = getParam(params, "TemplateData");
|
||||
|
||||
boolean hasName = templateName != null && !templateName.isBlank();
|
||||
boolean hasArn = templateArn != null && !templateArn.isBlank();
|
||||
if (!hasName && !hasArn) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Template or TemplateArn is required.", 400);
|
||||
}
|
||||
String resolvedName = hasName ? templateName : SesService.templateNameFromArn(templateArn);
|
||||
|
||||
JsonNode templateData = parseTemplateData(templateDataRaw);
|
||||
String messageId = sesService.sendTemplatedEmail(source, toAddresses, ccAddresses,
|
||||
bccAddresses, replyToAddresses, resolvedName, templateData, region);
|
||||
|
||||
String result = new XmlBuilder().elem("MessageId", messageId).build();
|
||||
return Response.ok(AwsQueryResponse.envelope("SendTemplatedEmail", AwsNamespaces.SES, result)).build();
|
||||
}
|
||||
|
||||
private EmailTemplate readTemplateParams(MultivaluedMap<String, String> params) {
|
||||
String name = getParam(params, "Template.TemplateName");
|
||||
String subject = getParam(params, "Template.SubjectPart");
|
||||
String text = getParam(params, "Template.TextPart");
|
||||
String html = getParam(params, "Template.HtmlPart");
|
||||
return new EmailTemplate(name, subject, text, html);
|
||||
}
|
||||
|
||||
private JsonNode parseTemplateData(String raw) {
|
||||
if (raw == null || raw.isBlank()) {
|
||||
return objectMapper.createObjectNode();
|
||||
}
|
||||
try {
|
||||
return objectMapper.readTree(raw);
|
||||
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
|
||||
throw new AwsException("InvalidTemplate",
|
||||
"Invalid TemplateData JSON: " + e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Helpers ---
|
||||
|
||||
private List<String> extractMembers(MultivaluedMap<String, String> params, String prefix) {
|
||||
|
||||
@@ -3,27 +3,36 @@ package io.github.hectorvent.floci.services.ses;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
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.SentEmail;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
public class SesService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SesService.class);
|
||||
|
||||
private static final Pattern TEMPLATE_VARIABLE = Pattern.compile("\\{\\{\\s*([\\w-]+)\\s*\\}\\}");
|
||||
|
||||
private final StorageBackend<String, Identity> identityStore;
|
||||
private final StorageBackend<String, SentEmail> emailStore;
|
||||
private final StorageBackend<String, Boolean> accountSettingsStore;
|
||||
private final StorageBackend<String, EmailTemplate> templateStore;
|
||||
private final SmtpRelay smtpRelay;
|
||||
|
||||
@Inject
|
||||
@@ -34,16 +43,20 @@ public class SesService {
|
||||
new TypeReference<Map<String, SentEmail>>() {});
|
||||
this.accountSettingsStore = storageFactory.create("ses", "ses-account-settings.json",
|
||||
new TypeReference<Map<String, Boolean>>() {});
|
||||
this.templateStore = storageFactory.create("ses", "ses-templates.json",
|
||||
new TypeReference<Map<String, EmailTemplate>>() {});
|
||||
this.smtpRelay = smtpRelay;
|
||||
}
|
||||
|
||||
SesService(StorageBackend<String, Identity> identityStore,
|
||||
StorageBackend<String, SentEmail> emailStore,
|
||||
StorageBackend<String, Boolean> accountSettingsStore,
|
||||
StorageBackend<String, EmailTemplate> templateStore,
|
||||
SmtpRelay smtpRelay) {
|
||||
this.identityStore = identityStore;
|
||||
this.emailStore = emailStore;
|
||||
this.accountSettingsStore = accountSettingsStore;
|
||||
this.templateStore = templateStore;
|
||||
this.smtpRelay = smtpRelay;
|
||||
}
|
||||
|
||||
@@ -239,6 +252,161 @@ public class SesService {
|
||||
LOG.infov("Updated account sending enabled for region {0}: {1}", region, enabled);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Templates ────────────────────────────
|
||||
|
||||
public EmailTemplate createTemplate(EmailTemplate template, String region) {
|
||||
validateTemplate(template);
|
||||
String key = templateKey(region, template.getTemplateName());
|
||||
if (templateStore.get(key).isPresent()) {
|
||||
throw new AwsException("AlreadyExists",
|
||||
"Template " + template.getTemplateName() + " already exists.", 400);
|
||||
}
|
||||
Instant now = Instant.now();
|
||||
template.setCreatedTimestamp(now);
|
||||
template.setLastUpdatedTimestamp(now);
|
||||
templateStore.put(key, template);
|
||||
LOG.infov("Created SES template: {0} in region {1}", template.getTemplateName(), region);
|
||||
return template;
|
||||
}
|
||||
|
||||
public EmailTemplate getTemplate(String templateName, String region) {
|
||||
return templateStore.get(templateKey(region, templateName))
|
||||
.orElseThrow(() -> new AwsException("TemplateDoesNotExist",
|
||||
"Template " + templateName + " does not exist.", 400));
|
||||
}
|
||||
|
||||
public EmailTemplate updateTemplate(EmailTemplate template, String region) {
|
||||
validateTemplate(template);
|
||||
String key = templateKey(region, template.getTemplateName());
|
||||
EmailTemplate existing = templateStore.get(key)
|
||||
.orElseThrow(() -> new AwsException("TemplateDoesNotExist",
|
||||
"Template " + template.getTemplateName() + " does not exist.", 400));
|
||||
template.setCreatedTimestamp(existing.getCreatedTimestamp());
|
||||
template.setLastUpdatedTimestamp(Instant.now());
|
||||
templateStore.put(key, template);
|
||||
LOG.infov("Updated SES template: {0} in region {1}", template.getTemplateName(), region);
|
||||
return template;
|
||||
}
|
||||
|
||||
public void deleteTemplate(String templateName, String region) {
|
||||
String key = templateKey(region, templateName);
|
||||
if (templateStore.get(key).isEmpty()) {
|
||||
throw new AwsException("TemplateDoesNotExist",
|
||||
"Template " + templateName + " does not exist.", 400);
|
||||
}
|
||||
templateStore.delete(key);
|
||||
LOG.infov("Deleted SES template: {0} in region {1}", templateName, region);
|
||||
}
|
||||
|
||||
public List<EmailTemplate> listTemplates(String region) {
|
||||
String prefix = "template::" + region + "::";
|
||||
List<EmailTemplate> all = new ArrayList<>(templateStore.scan(k -> k.startsWith(prefix)));
|
||||
all.sort(Comparator.comparing(EmailTemplate::getCreatedTimestamp,
|
||||
Comparator.nullsLast(Comparator.naturalOrder()))
|
||||
.thenComparing(EmailTemplate::getTemplateName,
|
||||
Comparator.nullsLast(Comparator.naturalOrder())));
|
||||
return all;
|
||||
}
|
||||
|
||||
public String sendTemplatedEmail(String source, List<String> toAddresses, List<String> ccAddresses,
|
||||
List<String> bccAddresses, List<String> replyToAddresses,
|
||||
String templateName, JsonNode templateData, String region) {
|
||||
EmailTemplate template = getTemplate(templateName, region);
|
||||
return sendInlineTemplatedEmail(source, toAddresses, ccAddresses, bccAddresses,
|
||||
replyToAddresses, template.getSubject(), template.getTextPart(),
|
||||
template.getHtmlPart(), templateData, region);
|
||||
}
|
||||
|
||||
public String sendInlineTemplatedEmail(String source, List<String> toAddresses, List<String> ccAddresses,
|
||||
List<String> bccAddresses, List<String> replyToAddresses,
|
||||
String subject, String textPart, String htmlPart,
|
||||
JsonNode templateData, String region) {
|
||||
boolean hasSubject = subject != null && !subject.isBlank();
|
||||
boolean hasText = textPart != null && !textPart.isBlank();
|
||||
boolean hasHtml = htmlPart != null && !htmlPart.isBlank();
|
||||
if (!hasSubject && !hasText && !hasHtml) {
|
||||
throw new AwsException("InvalidTemplate",
|
||||
"Template must have at least a subject, text, or html part.", 400);
|
||||
}
|
||||
return sendEmail(source, toAddresses, ccAddresses, bccAddresses, replyToAddresses,
|
||||
applyTemplateData(subject, templateData),
|
||||
applyTemplateData(textPart, templateData),
|
||||
applyTemplateData(htmlPart, templateData),
|
||||
region);
|
||||
}
|
||||
|
||||
static String applyTemplateData(String text, JsonNode data) {
|
||||
if (text == null || text.isEmpty()) {
|
||||
return text;
|
||||
}
|
||||
Matcher matcher = TEMPLATE_VARIABLE.matcher(text);
|
||||
StringBuilder out = new StringBuilder();
|
||||
while (matcher.find()) {
|
||||
String key = matcher.group(1);
|
||||
String replacement = "";
|
||||
if (data != null && data.hasNonNull(key)) {
|
||||
JsonNode value = data.get(key);
|
||||
replacement = value.isValueNode() ? value.asText() : value.toString();
|
||||
}
|
||||
matcher.appendReplacement(out, Matcher.quoteReplacement(replacement));
|
||||
}
|
||||
matcher.appendTail(out);
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static void validateTemplate(EmailTemplate template) {
|
||||
if (template == null) {
|
||||
throw new AwsException("InvalidTemplate", "Template is required.", 400);
|
||||
}
|
||||
validateTemplateName(template.getTemplateName());
|
||||
boolean hasSubject = template.getSubject() != null && !template.getSubject().isBlank();
|
||||
boolean hasText = template.getTextPart() != null && !template.getTextPart().isBlank();
|
||||
boolean hasHtml = template.getHtmlPart() != null && !template.getHtmlPart().isBlank();
|
||||
if (!hasSubject && !hasText && !hasHtml) {
|
||||
throw new AwsException("InvalidTemplate",
|
||||
"Template must have at least a subject, text, or html part.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateTemplateName(String templateName) {
|
||||
if (templateName == null || templateName.isBlank()) {
|
||||
throw new AwsException("InvalidTemplate", "TemplateName is required.", 400);
|
||||
}
|
||||
if (Character.isWhitespace(templateName.charAt(0))
|
||||
|| Character.isWhitespace(templateName.charAt(templateName.length() - 1))) {
|
||||
throw new AwsException("InvalidTemplate",
|
||||
"TemplateName must not contain leading or trailing whitespace.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static String templateKey(String region, String templateName) {
|
||||
validateTemplateName(templateName);
|
||||
return "template::" + region + "::" + templateName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the template name from an SES template ARN of the form
|
||||
* {@code arn:aws:ses:<region>:<account>:template/<name>}. Region and
|
||||
* account segments are not validated; only the {@code template/<name>}
|
||||
* suffix is required.
|
||||
*/
|
||||
public static String templateNameFromArn(String arn) {
|
||||
if (arn == null || arn.isBlank()) {
|
||||
throw new AwsException("InvalidParameterValue", "TemplateArn is required.", 400);
|
||||
}
|
||||
int marker = arn.indexOf(":template/");
|
||||
if (!arn.startsWith("arn:") || marker < 0) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"TemplateArn is not a valid SES template ARN: " + arn, 400);
|
||||
}
|
||||
String name = arn.substring(marker + ":template/".length());
|
||||
if (name.isEmpty()) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"TemplateArn is missing a template name: " + arn, 400);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
private static String identityKey(String region, String identity) {
|
||||
validateIdentityWhitespace(identity, "Identity");
|
||||
return "identity::" + region + "::" + identity;
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package io.github.hectorvent.floci.services.ses.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class EmailTemplate {
|
||||
|
||||
@JsonProperty("TemplateName")
|
||||
private String templateName;
|
||||
|
||||
@JsonProperty("Subject")
|
||||
private String subject;
|
||||
|
||||
@JsonProperty("TextPart")
|
||||
private String textPart;
|
||||
|
||||
@JsonProperty("HtmlPart")
|
||||
private String htmlPart;
|
||||
|
||||
@JsonProperty("CreatedTimestamp")
|
||||
private Instant createdTimestamp;
|
||||
|
||||
@JsonProperty("LastUpdatedTimestamp")
|
||||
private Instant lastUpdatedTimestamp;
|
||||
|
||||
public EmailTemplate() {}
|
||||
|
||||
public EmailTemplate(String templateName, String subject, String textPart, String htmlPart) {
|
||||
this.templateName = templateName;
|
||||
this.subject = subject;
|
||||
this.textPart = textPart;
|
||||
this.htmlPart = htmlPart;
|
||||
}
|
||||
|
||||
public String getTemplateName() { return templateName; }
|
||||
public void setTemplateName(String templateName) { this.templateName = templateName; }
|
||||
|
||||
public String getSubject() { return subject; }
|
||||
public void setSubject(String subject) { this.subject = subject; }
|
||||
|
||||
public String getTextPart() { return textPart; }
|
||||
public void setTextPart(String textPart) { this.textPart = textPart; }
|
||||
|
||||
public String getHtmlPart() { return htmlPart; }
|
||||
public void setHtmlPart(String htmlPart) { this.htmlPart = htmlPart; }
|
||||
|
||||
public Instant getCreatedTimestamp() { return createdTimestamp; }
|
||||
public void setCreatedTimestamp(Instant createdTimestamp) { this.createdTimestamp = createdTimestamp; }
|
||||
|
||||
public Instant getLastUpdatedTimestamp() { return lastUpdatedTimestamp; }
|
||||
public void setLastUpdatedTimestamp(Instant lastUpdatedTimestamp) { this.lastUpdatedTimestamp = lastUpdatedTimestamp; }
|
||||
}
|
||||
Reference in new issue
Block a user