feat(ses): add TestRenderTemplate (v1) and TestRenderEmailTemplate (v2) (#692)

* feat(ses): add TestRenderTemplate (v1) and TestRenderEmailTemplate (v2)

Render a stored SES template against caller-supplied data and return the
resulting MIME message. v1 is dispatched via the Query protocol; v2 is
exposed at POST /v2/email/templates/{name}/render.

Template variable substitution is now strict: a missing attribute in the
rendering data raises MissingRenderingAttribute (mapped to BadRequestException
on v2), matching AWS / moto / LocalStack semantics. Invalid TemplateData
JSON raises InvalidRenderingParameter; non-object TemplateData is rejected
with operation-appropriate errors on the send paths (InvalidParameterValue
on v1, BadRequestException on v2).

The rendered output is a hand-rolled multipart/alternative MIME with a
Date header (UTC), Subject header, and text/plain + text/html parts.
Transfer encoding is auto-selected (7bit for ASCII bodies, 8bit for UTF-8)
matching moto's encode_7or8bit. Body line endings are normalized to CRLF.
Subject control characters and XML 1.0 invalid characters in the rendered
output are stripped to keep the response parseable by SDK clients.

Bulk per-entry rendering errors (MissingRenderingAttribute /
InvalidRenderingParameter raised at apply time) surface as INVALID_PARAMETER
in BulkEmailEntryResults rather than generic FAILED.

No new dependencies are introduced.

* test(ses): consolidate new SesServiceTemplateTest cases via @ParameterizedTest

Group 23 of the new unit tests added in this PR into 6
@ParameterizedTest methods driven by MethodSource data sets:

- pickTransferEncoding (ascii vs non-ascii) -> 1 test, 4 cases
- parseRenderingData invalid inputs -> 1 test, 5 cases
- normalizeToCrlf line-ending variants -> 1 test, 4 cases
- mapErrorCodeToBulkStatus -> 1 test, 4 cases
- sanitizeSubject control / DEL / Unicode preservation -> 1 test,
  6 cases (null-input case kept separate)
- stripXml10InvalidChars C0 / noncharacters / surrogates -> 1 test,
  11 cases

Coverage is preserved (every input that was exercised before is still
exercised; surfacing each case as an individual test makes the run
report show 58 cases instead of 49 for this file). The remaining
tests -- buildTestRenderMime structure assertions and the original
applyTemplateData edge cases -- stay as individual @Test methods
because they have distinct multi-step assertions.

* test(ses): address upstream Copilot style nits

- Remove unused containsString static import in
  SesTestRenderV2IntegrationTest after the parameterized refactor
- Replace assertEquals(true/false, ...) with assertTrue/assertFalse in
  SesServiceTemplateTest for clearer intent and better failure output
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-05-03 09:18:10 -05:00
1 parent db9eedc4cd
commit ac891db5a7
14 files changed
+1368 -32

No files matched your search

@@ -302,6 +302,7 @@ public class AwsQueryController {
"GetIdentityDkimAttributes",
"CreateTemplate", "UpdateTemplate", "GetTemplate", "DeleteTemplate",
"ListTemplates", "SendTemplatedEmail", "SendBulkTemplatedEmail",
"TestRenderTemplate",
"CreateConfigurationSet", "DescribeConfigurationSet",
"ListConfigurationSets", "DeleteConfigurationSet"
);
@@ -194,6 +194,7 @@ public class SesController {
}
JsonNode request = objectMapper.readTree(body);
requireJsonObject(request);
String fromEmailAddress = request.path("FromEmailAddress").asText(null);
if (fromEmailAddress == null || fromEmailAddress.isBlank()) {
@@ -201,7 +202,7 @@ public class SesController {
"FromEmailAddress is required.", 400);
}
JsonNode destination = request.path("Destination");
JsonNode destination = requireObjectOrAbsent(request, "Destination");
List<String> toAddresses = jsonArrayToList(destination.path("ToAddresses"));
List<String> ccAddresses = jsonArrayToList(destination.path("CcAddresses"));
List<String> bccAddresses = jsonArrayToList(destination.path("BccAddresses"));
@@ -246,7 +247,7 @@ public class SesController {
throw new AwsException("BadRequestException",
"Content.Template requires TemplateName, TemplateArn, or TemplateContent.", 400);
}
JsonNode templateData = parseTemplateData(template.path("TemplateData").asText(""));
JsonNode templateData = parseTemplateData(template, "TemplateData");
if (hasName || hasArn) {
String resolvedName = hasName
? templateName
@@ -291,6 +292,7 @@ public class SesController {
}
JsonNode request = objectMapper.readTree(body);
requireJsonObject(request);
String fromEmailAddress = request.path("FromEmailAddress").asText(null);
if (fromEmailAddress == null || fromEmailAddress.isBlank()) {
throw new AwsException("BadRequestException",
@@ -337,7 +339,7 @@ public class SesController {
html = stored.getHtmlPart();
}
JsonNode defaultTemplateData = parseTemplateData(template.path("TemplateData").asText(""));
JsonNode defaultTemplateData = parseTemplateData(template, "TemplateData");
JsonNode bulkEntries = request.path("BulkEmailEntries");
if (!bulkEntries.isArray() || bulkEntries.isEmpty()) {
@@ -347,15 +349,18 @@ public class SesController {
List<BulkEmailEntry> entries = new ArrayList<>();
for (JsonNode node : bulkEntries) {
JsonNode dest = node.path("Destination");
if (!node.isObject()) {
throw new AwsException("BadRequestException",
"BulkEmailEntries elements must be JSON objects.", 400);
}
JsonNode dest = requireObjectOrAbsent(node, "Destination");
List<String> to = jsonArrayToList(dest.path("ToAddresses"));
List<String> cc = jsonArrayToList(dest.path("CcAddresses"));
List<String> bcc = jsonArrayToList(dest.path("BccAddresses"));
String replacementRaw = node.path("ReplacementEmailContent")
.path("ReplacementTemplate")
.path("ReplacementTemplateData")
.asText("");
entries.add(new BulkEmailEntry(to, cc, bcc, parseTemplateData(replacementRaw)));
JsonNode replacementContent = requireObjectOrAbsent(node, "ReplacementEmailContent");
JsonNode replacementTemplate = requireObjectOrAbsent(replacementContent, "ReplacementTemplate");
JsonNode replacementData = parseTemplateData(replacementTemplate, "ReplacementTemplateData");
entries.add(new BulkEmailEntry(to, cc, bcc, replacementData));
}
List<BulkEmailEntryResult> results = sesService.sendBulkTemplatedEmail(fromEmailAddress,
@@ -473,6 +478,36 @@ public class SesController {
}
}
@POST
@Path("/templates/{templateName}/render")
public Response testRenderEmailTemplate(@Context HttpHeaders headers,
@PathParam("templateName") String templateName,
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 templateDataNode = request.path("TemplateData");
if (!templateDataNode.isMissingNode() && !templateDataNode.isNull()
&& !templateDataNode.isTextual()) {
throw new AwsException("BadRequestException",
"TemplateData must be a JSON-encoded string.", 400);
}
String templateDataRaw = templateDataNode.asText("");
String rendered = sesService.renderTestTemplate(templateName, templateDataRaw, region);
ObjectNode result = objectMapper.createObjectNode();
result.put("RenderedTemplate", rendered);
return Response.ok(result).build();
} catch (AwsException e) {
throw remapV1Exception(e);
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
// ──────────────────────── Configuration Sets ───────────────────────
@POST
@@ -688,21 +723,63 @@ public class SesController {
return result;
}
private JsonNode parseTemplateData(JsonNode parent, String fieldName) {
if (parent == null || parent.isMissingNode() || parent.isNull()) {
return objectMapper.createObjectNode();
}
if (!parent.isObject()) {
throw new AwsException("BadRequestException",
"Parent of " + fieldName + " must be a JSON object.", 400);
}
JsonNode field = parent.path(fieldName);
if (field.isMissingNode() || field.isNull()) {
return objectMapper.createObjectNode();
}
if (!field.isTextual()) {
throw new AwsException("BadRequestException",
fieldName + " must be a JSON-encoded string.", 400);
}
return parseTemplateData(field.asText(""));
}
private JsonNode parseTemplateData(String raw) {
if (raw == null || raw.isBlank()) {
return objectMapper.createObjectNode();
}
JsonNode node;
try {
return objectMapper.readTree(raw);
node = objectMapper.readTree(raw);
} catch (Exception e) {
throw new AwsException("BadRequestException",
"Invalid TemplateData JSON: " + e.getMessage(), 400);
}
if (!node.isObject()) {
throw new AwsException("BadRequestException",
"TemplateData must be a JSON object.", 400);
}
return node;
}
private static void requireJsonObject(JsonNode root) {
if (root == null || !root.isObject()) {
throw new AwsException("BadRequestException",
"Request body must be a JSON object.", 400);
}
}
private static JsonNode requireObjectOrAbsent(JsonNode parent, String fieldName) {
JsonNode child = parent.path(fieldName);
if (!child.isMissingNode() && !child.isNull() && !child.isObject()) {
throw new AwsException("BadRequestException",
fieldName + " must be a JSON object.", 400);
}
return child;
}
private static AwsException remapV1Exception(AwsException e) {
return switch (e.getErrorCode()) {
case "InvalidParameterValue", "InvalidTemplate" ->
case "InvalidParameterValue", "InvalidTemplate",
"InvalidRenderingParameter", "MissingRenderingAttribute" ->
new AwsException("BadRequestException", e.getMessage(), 400);
case "TemplateDoesNotExist", "ConfigurationSetDoesNotExist" ->
new AwsException("NotFoundException", e.getMessage(), 404);
@@ -66,6 +66,7 @@ public class SesQueryHandler {
case "ListTemplates" -> handleListTemplates(region);
case "SendTemplatedEmail" -> handleSendTemplatedEmail(params, region);
case "SendBulkTemplatedEmail" -> handleSendBulkTemplatedEmail(params, region);
case "TestRenderTemplate" -> handleTestRenderTemplate(params, region);
case "CreateConfigurationSet" -> handleCreateConfigurationSet(params, region);
case "DescribeConfigurationSet" -> handleDescribeConfigurationSet(params, region);
case "ListConfigurationSets" -> handleListConfigurationSets(region);
@@ -356,6 +357,20 @@ public class SesQueryHandler {
return Response.ok(AwsQueryResponse.envelope("SendTemplatedEmail", AwsNamespaces.SES, result)).build();
}
private Response handleTestRenderTemplate(MultivaluedMap<String, String> params, String region) {
String templateName = getParam(params, "TemplateName");
if (templateName == null || templateName.isBlank()) {
throw new AwsException("InvalidParameterValue", "TemplateName is required.", 400);
}
String templateDataRaw = getParam(params, "TemplateData");
String rendered = sesService.renderTestTemplate(templateName, templateDataRaw, region);
// XML 1.0 character data forbids C0 controls except \t \n \r; strip them
// so SDK clients can parse the response when template data injects \x01 etc.
String xmlSafe = SesService.stripXml10InvalidChars(rendered);
String result = new XmlBuilder().elem("RenderedTemplate", xmlSafe).build();
return Response.ok(AwsQueryResponse.envelope("TestRenderTemplate", AwsNamespaces.SES, result)).build();
}
private Response handleSendBulkTemplatedEmail(MultivaluedMap<String, String> params, String region) {
if (!sesService.isAccountSendingEnabled(region)) {
throw new AwsException("AccountSendingPausedException",
@@ -467,12 +482,18 @@ public class SesQueryHandler {
if (raw == null || raw.isBlank()) {
return objectMapper.createObjectNode();
}
JsonNode node;
try {
return objectMapper.readTree(raw);
node = objectMapper.readTree(raw);
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
throw new AwsException("InvalidTemplate",
"Invalid TemplateData JSON: " + e.getMessage(), 400);
}
if (!node.isObject()) {
throw new AwsException("InvalidParameterValue",
"TemplateData must be a JSON object.", 400);
}
return node;
}
// --- Helpers ---
@@ -11,15 +11,21 @@ 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 com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.security.SecureRandom;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@@ -36,15 +42,18 @@ public class SesService {
private static final int MAX_BULK_DESTINATIONS = 50;
private static final int MAX_RECIPIENTS_PER_DESTINATION = 50;
private static final SecureRandom BOUNDARY_RANDOM = new SecureRandom();
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 StorageBackend<String, ConfigurationSet> configSetStore;
private final SmtpRelay smtpRelay;
private final ObjectMapper objectMapper;
@Inject
public SesService(StorageFactory storageFactory, SmtpRelay smtpRelay) {
public SesService(StorageFactory storageFactory, SmtpRelay smtpRelay, ObjectMapper objectMapper) {
this.identityStore = storageFactory.create("ses", "ses-identities.json",
new TypeReference<Map<String, Identity>>() {});
this.emailStore = storageFactory.create("ses", "ses-emails.json",
@@ -56,6 +65,7 @@ public class SesService {
this.configSetStore = storageFactory.create("ses", "ses-config-sets.json",
new TypeReference<Map<String, ConfigurationSet>>() {});
this.smtpRelay = smtpRelay;
this.objectMapper = objectMapper;
}
SesService(StorageBackend<String, Identity> identityStore,
@@ -63,13 +73,15 @@ public class SesService {
StorageBackend<String, Boolean> accountSettingsStore,
StorageBackend<String, EmailTemplate> templateStore,
StorageBackend<String, ConfigurationSet> configSetStore,
SmtpRelay smtpRelay) {
SmtpRelay smtpRelay,
ObjectMapper objectMapper) {
this.identityStore = identityStore;
this.emailStore = emailStore;
this.accountSettingsStore = accountSettingsStore;
this.templateStore = templateStore;
this.configSetStore = configSetStore;
this.smtpRelay = smtpRelay;
this.objectMapper = objectMapper;
}
public Identity verifyEmailIdentity(String emailAddress, String region) {
@@ -416,6 +428,119 @@ public class SesService {
template.getHtmlPart(), templateData, region);
}
public String renderTestTemplate(String templateName, String templateDataRaw, String region) {
EmailTemplate template = getTemplate(templateName, region);
JsonNode templateData = parseRenderingData(objectMapper, templateDataRaw);
String subject = applyTemplateData(template.getSubject(), templateData);
String text = applyTemplateData(template.getTextPart(), templateData);
String html = applyTemplateData(template.getHtmlPart(), templateData);
return buildTestRenderMime(subject, text, html, ZonedDateTime.now(ZoneOffset.UTC), nextBoundary());
}
static JsonNode parseRenderingData(ObjectMapper mapper, String raw) {
if (raw == null || raw.isBlank()) {
throw new AwsException("InvalidRenderingParameter",
"Template rendering data is required.", 400);
}
JsonNode node;
try {
node = mapper.readTree(raw);
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
throw new AwsException("InvalidRenderingParameter",
"Template rendering data is invalid: " + e.getOriginalMessage(), 400);
}
if (!node.isObject()) {
throw new AwsException("InvalidRenderingParameter",
"Template rendering data must be a JSON object.", 400);
}
return node;
}
static String buildTestRenderMime(String subject, String text, String html,
ZonedDateTime date, String boundary) {
String safeSubject = sanitizeSubject(subject);
String safeText = text == null ? "" : text;
String safeHtml = html == null ? "" : html;
String dateHeader = DateTimeFormatter.RFC_1123_DATE_TIME.format(date);
StringBuilder out = new StringBuilder();
out.append("Date: ").append(dateHeader).append("\r\n");
out.append("Subject: ").append(safeSubject).append("\r\n");
out.append("MIME-Version: 1.0\r\n");
out.append("Content-Type: multipart/alternative; boundary=\"").append(boundary).append("\"\r\n");
out.append("\r\n");
appendMimePart(out, boundary, "text/plain", safeText);
appendMimePart(out, boundary, "text/html", safeHtml);
out.append("--").append(boundary).append("--\r\n");
return out.toString();
}
private static void appendMimePart(StringBuilder out, String boundary, String mimeType, String body) {
out.append("--").append(boundary).append("\r\n");
out.append("Content-Type: ").append(mimeType).append("; charset=UTF-8\r\n");
out.append("Content-Transfer-Encoding: ").append(pickTransferEncoding(body)).append("\r\n");
out.append("\r\n");
String normalized = normalizeToCrlf(body);
out.append(normalized);
if (!normalized.endsWith("\r\n")) {
out.append("\r\n");
}
}
static String normalizeToCrlf(String body) {
return body.replace("\r\n", "\n").replace("\r", "\n").replace("\n", "\r\n");
}
static String pickTransferEncoding(String body) {
return body.codePoints().allMatch(c -> c < 128) ? "7bit" : "8bit";
}
static String sanitizeSubject(String subject) {
if (subject == null) {
return "";
}
// Strip C0 control characters (U+0000-U+001F) and DEL (U+007F): RFC 5322
// forbids them in unstructured header field bodies. Replace with spaces so
// visible content is preserved when template data accidentally injects them.
StringBuilder out = new StringBuilder(subject.length());
for (int i = 0; i < subject.length(); i++) {
char c = subject.charAt(i);
out.append((c < 0x20 || c == 0x7F) ? ' ' : c);
}
return out.toString();
}
static String stripXml10InvalidChars(String s) {
if (s == null || s.isEmpty()) {
return s;
}
// XML 1.0 char production: \t \n \r, U+0020-U+D7FF, U+E000-U+FFFD,
// U+10000-U+10FFFF. Anything else (C0 controls, U+FFFE/U+FFFF, lone
// surrogates) makes the response unparseable by SDK XML parsers.
StringBuilder out = new StringBuilder(s.length());
int i = 0;
while (i < s.length()) {
int cp = s.codePointAt(i);
if (isXml10Char(cp)) {
out.appendCodePoint(cp);
}
i += Character.charCount(cp);
}
return out.toString();
}
private static boolean isXml10Char(int cp) {
return cp == 0x09 || cp == 0x0A || cp == 0x0D
|| (cp >= 0x20 && cp <= 0xD7FF)
|| (cp >= 0xE000 && cp <= 0xFFFD)
|| (cp >= 0x10000 && cp <= 0x10FFFF);
}
private static String nextBoundary() {
byte[] bytes = new byte[6];
BOUNDARY_RANDOM.nextBytes(bytes);
return "===_floci_" + HexFormat.of().formatHex(bytes) + "_===";
}
public String sendInlineTemplatedEmail(String source, List<String> toAddresses, List<String> ccAddresses,
List<String> bccAddresses, List<String> replyToAddresses,
String subject, String textPart, String htmlPart,
@@ -497,7 +622,9 @@ public class SesService {
}
static BulkEmailEntryResult.Status mapErrorCodeToBulkStatus(String errorCode) {
if ("InvalidParameterValue".equals(errorCode)) {
if ("InvalidParameterValue".equals(errorCode)
|| "MissingRenderingAttribute".equals(errorCode)
|| "InvalidRenderingParameter".equals(errorCode)) {
return BulkEmailEntryResult.Status.INVALID_PARAMETER;
}
return BulkEmailEntryResult.Status.FAILED;
@@ -534,11 +661,12 @@ public class SesService {
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();
if (data == null || !data.hasNonNull(key)) {
throw new AwsException("MissingRenderingAttribute",
"Attribute '" + key + "' is not present in the rendering data.", 400);
}
JsonNode value = data.get(key);
String replacement = value.isValueNode() ? value.asText() : value.toString();
matcher.appendReplacement(out, Matcher.quoteReplacement(replacement));
}
matcher.appendTail(out);