fix(ses): require a subject and a part to create or update a template (#8840)

This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-11-18 07:18:54 -04:00
1 parent e5ddc9fffc
commit 51fd7950e1
8 files changed
+282 -28

No files matched your search

@@ -558,7 +558,7 @@ public class SesQueryHandler {
private Response handleCreateTemplate(MultivaluedMap<String, String> params, String region) {
EmailTemplate template = readTemplateParams(params);
templateService.createTemplate(template, region);
templateService.createTemplate(template, region, regionResolver.getAccountId());
return Response.ok(AwsQueryResponse.envelopeEmptyResult("CreateTemplate", AwsNamespaces.SES)).build();
}
@@ -74,7 +74,7 @@ public class SesTemplateController {
if (parsedTags != null) {
template.setTags(parsedTags);
}
templateService.createTemplate(template, region);
templateService.createTemplate(template, region, regionResolver.getAccountId());
LOG.infov("SES V2 CreateEmailTemplate: {0}", templateName);
return Response.ok(objectMapper.createObjectNode()).build();
} catch (AwsException e) {
@@ -84,13 +84,14 @@ public class SesTemplateService implements SesTaggable {
this.clock = clock;
}
public EmailTemplate createTemplate(EmailTemplate template, String region) {
public EmailTemplate createTemplate(EmailTemplate template, String region, String accountId) {
validateTemplate(template);
dropEmptyParts(template);
SesTags.validate(template.getTags());
String key = templateKey(region, template.getTemplateName());
if (templateStore.get(key).isPresent()) {
throw new AwsException("AlreadyExists",
"Template " + template.getTemplateName() + " already exists.", 400);
"Template " + template.getTemplateName() + " already exists for account id " + accountId, 400);
}
Instant now = Instant.now(clock);
template.setCreatedTimestamp(now);
@@ -114,6 +115,7 @@ public class SesTemplateService implements SesTaggable {
public EmailTemplate updateTemplate(EmailTemplate template, String region) {
validateTemplate(template);
dropEmptyParts(template);
String key = templateKey(region, template.getTemplateName());
EmailTemplate existing = templateStore.get(key)
.orElseThrow(() -> new AwsException("TemplateDoesNotExist",
@@ -176,12 +178,28 @@ public class SesTemplateService implements SesTaggable {
throw new AwsException("InvalidTemplate", "Template is required.", 400);
}
validateTemplateName(template.getTemplateName());
boolean hasSubject = template.getSubject() != null && !template.getSubject().isBlank();
// SES asks for the subject first, then for a part, and a blank value counts as missing.
if (template.getSubject() == null || template.getSubject().isBlank()) {
throw new AwsException("InvalidParameterValue", "The subject must be specified.", 400);
}
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);
if (!hasText && !hasHtml) {
throw new AwsException("InvalidParameterValue",
"Template must specify at least one of the parts.", 400);
}
}
/**
* SES stores an empty part as no part: a template sent with {@code Text: ""} beside an HTML
* part reads back without {@code Text}. A whitespace-only part beside another one is kept.
*/
private static void dropEmptyParts(EmailTemplate template) {
if (template.getTextPart() != null && template.getTextPart().isEmpty()) {
template.setTextPart(null);
}
if (template.getHtmlPart() != null && template.getHtmlPart().isEmpty()) {
template.setHtmlPart(null);
}
}
@@ -36,8 +36,7 @@ class SesNonObjectBodyIntegrationTest {
return Stream.of(
Arguments.of("POST", "/v2/email/identities", "EmailIdentity is required."),
Arguments.of("POST", "/v2/email/templates", "TemplateName is required."),
Arguments.of("PUT", "/v2/email/templates/non-object-ghost",
"Template must have at least a subject, text, or html part."),
Arguments.of("PUT", "/v2/email/templates/non-object-ghost", "The subject must be specified."),
Arguments.of("POST", "/v2/email/custom-verification-email-templates", "TemplateName is required."),
Arguments.of("PUT", "/v2/email/custom-verification-email-templates/non-object-ghost",
"FromEmailAddress is required."),
@@ -0,0 +1,148 @@
package io.floci.aws.services.ses;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.stream.Stream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
/**
* What a template must carry to be created or updated, as probed on us-west-2: a subject, then at
* least one part with a character that is not whitespace, both asked for before the name is looked up.
*/
@QuarkusTest
class SesTemplateRequiredPartsIntegrationTest {
private static final String V1_AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request";
private static final String V2_AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request";
private static final String NO_SUBJECT = "The subject must be specified.";
private static final String NO_PART = "Template must specify at least one of the parts.";
static Stream<Arguments> refusedV2Contents() {
return Stream.of(
Arguments.of("{}", NO_SUBJECT),
Arguments.of("{\"Text\": \"t\", \"Html\": \"<p>h</p>\"}", NO_SUBJECT),
Arguments.of("{\"Subject\": \" \", \"Text\": \"t\"}", NO_SUBJECT),
Arguments.of("{\"Subject\": \"S\"}", NO_PART),
Arguments.of("{\"Subject\": \"S\", \"Text\": \" \", \"Html\": \"\"}", NO_PART));
}
@ParameterizedTest
@MethodSource("refusedV2Contents")
void v2Create_refusesTheContent(String content, String message) {
given()
.contentType("application/json")
.header("Authorization", V2_AUTH)
.body("{\"TemplateName\": \"required-parts-refused\", \"TemplateContent\": " + content + "}")
.when()
.post("/v2/email/templates")
.then()
.statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo(message));
}
@ParameterizedTest
@MethodSource("refusedV2Contents")
void v2Update_refusesTheContentOfAnUnknownTemplate(String content, String message) {
given()
.contentType("application/json")
.header("Authorization", V2_AUTH)
.body("{\"TemplateContent\": " + content + "}")
.when()
.put("/v2/email/templates/required-parts-ghost")
.then()
.statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo(message));
}
@Test
void v2Create_readsAnEmptyPartBackAsNoPart() {
given()
.contentType("application/json")
.header("Authorization", V2_AUTH)
.body("""
{"TemplateName": "required-parts-html-only",
"TemplateContent": {"Subject": "S", "Text": "", "Html": "<p>h</p>"}}
""")
.when()
.post("/v2/email/templates")
.then()
.statusCode(200);
given()
.header("Authorization", V2_AUTH)
.when()
.get("/v2/email/templates/required-parts-html-only")
.then()
.statusCode(200)
.body("TemplateContent.Html", equalTo("<p>h</p>"))
.body("TemplateContent.Text", nullValue());
given()
.header("Authorization", V2_AUTH)
.when()
.delete("/v2/email/templates/required-parts-html-only")
.then()
.statusCode(200);
}
@Test
void v1Create_requiresASubject() {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", V1_AUTH)
.formParam("Action", "CreateTemplate")
.formParam("Template.TemplateName", "required-parts-v1")
.formParam("Template.TextPart", "t")
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("<Code>InvalidParameterValue</Code>"))
.body(containsString("<Message>" + NO_SUBJECT + "</Message>"));
}
@Test
void v1Create_requiresAPart() {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", V1_AUTH)
.formParam("Action", "CreateTemplate")
.formParam("Template.TemplateName", "required-parts-v1")
.formParam("Template.SubjectPart", "S")
.formParam("Template.TextPart", " ")
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("<Code>InvalidParameterValue</Code>"))
.body(containsString("<Message>" + NO_PART + "</Message>"));
}
@Test
void v1Update_requiresAPartBeforeTheTemplateIsLookedUp() {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", V1_AUTH)
.formParam("Action", "UpdateTemplate")
.formParam("Template.TemplateName", "required-parts-ghost")
.formParam("Template.SubjectPart", "S")
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("<Code>InvalidParameterValue</Code>"))
.body(containsString("<Message>" + NO_PART + "</Message>"));
}
}
@@ -37,6 +37,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class SesTemplateServiceTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private SesTemplateService service;
@BeforeEach
@@ -51,7 +52,7 @@ class SesTemplateServiceTest {
@Test
void create_thenGet_roundTrips() {
EmailTemplate created = service.createTemplate(template("welcome"), REGION);
EmailTemplate created = service.createTemplate(template("welcome"), REGION, ACCOUNT);
assertNotNull(created.getCreatedTimestamp());
assertNotNull(created.getLastUpdatedTimestamp());
@@ -61,19 +62,103 @@ class SesTemplateServiceTest {
@Test
void create_rejectsDuplicate() {
service.createTemplate(template("welcome"), REGION);
assertThrows(AwsException.class, () -> service.createTemplate(template("welcome"), REGION));
service.createTemplate(template("welcome"), REGION, ACCOUNT);
AwsException e = assertThrows(AwsException.class,
() -> service.createTemplate(template("welcome"), REGION, ACCOUNT));
assertEquals("AlreadyExists", e.getErrorCode());
assertEquals("Template welcome already exists for account id " + ACCOUNT, e.getMessage());
}
// probed: the subject is asked for first, and a blank one counts as missing
@ParameterizedTest
@MethodSource("templatesWithoutSubject")
void createAndUpdate_requireASubject(String subject, String text, String html) {
service.createTemplate(template("stored"), REGION, ACCOUNT);
AwsException onCreate = assertThrows(AwsException.class,
() -> service.createTemplate(new EmailTemplate("fresh", subject, text, html), REGION, ACCOUNT));
assertEquals("InvalidParameterValue", onCreate.getErrorCode());
assertEquals("The subject must be specified.", onCreate.getMessage());
AwsException onUpdate = assertThrows(AwsException.class,
() -> service.updateTemplate(new EmailTemplate("stored", subject, text, html), REGION));
assertEquals("InvalidParameterValue", onUpdate.getErrorCode());
assertEquals("The subject must be specified.", onUpdate.getMessage());
}
static Stream<Arguments> templatesWithoutSubject() {
return Stream.of(
Arguments.of(null, null, null),
Arguments.of(null, "t", null),
Arguments.of(null, null, "<p>h</p>"),
Arguments.of(null, "t", "<p>h</p>"),
Arguments.of("", "t", null),
Arguments.of(" ", "t", null),
Arguments.of(null, " ", null));
}
// probed: a part counts only when it has a character that is not whitespace
@ParameterizedTest
@MethodSource("templatesWithoutParts")
void createAndUpdate_requireOnePart(String text, String html) {
service.createTemplate(template("stored"), REGION, ACCOUNT);
AwsException onCreate = assertThrows(AwsException.class,
() -> service.createTemplate(new EmailTemplate("fresh", "S", text, html), REGION, ACCOUNT));
assertEquals("InvalidParameterValue", onCreate.getErrorCode());
assertEquals("Template must specify at least one of the parts.", onCreate.getMessage());
AwsException onUpdate = assertThrows(AwsException.class,
() -> service.updateTemplate(new EmailTemplate("stored", "S", text, html), REGION));
assertEquals("InvalidParameterValue", onUpdate.getErrorCode());
assertEquals("Template must specify at least one of the parts.", onUpdate.getMessage());
assertEquals("text body", service.getTemplate("stored", REGION).getTextPart());
}
static Stream<Arguments> templatesWithoutParts() {
return Stream.of(
Arguments.of(null, null),
Arguments.of("", null),
Arguments.of(" ", null),
Arguments.of(null, "\n"),
Arguments.of(" ", ""));
}
// probed: the content is checked before the name is looked up, on both operations
@Test
void contentIsCheckedBeforeTheTemplateIsLookedUp() {
service.createTemplate(template("stored"), REGION, ACCOUNT);
AwsException duplicate = assertThrows(AwsException.class,
() -> service.createTemplate(new EmailTemplate("stored", "S", null, null), REGION, ACCOUNT));
assertEquals("Template must specify at least one of the parts.", duplicate.getMessage());
AwsException unknown = assertThrows(AwsException.class,
() -> service.updateTemplate(new EmailTemplate("ghost", "S", null, null), REGION));
assertEquals("Template must specify at least one of the parts.", unknown.getMessage());
}
// probed: an empty part beside a real one is accepted and read back as no part, on both operations
@Test
void emptyPartIsStoredAsNoPart() {
service.createTemplate(new EmailTemplate("html-only", "S", "", "<p>h</p>"), REGION, ACCOUNT);
assertNull(service.getTemplate("html-only", REGION).getTextPart());
service.updateTemplate(new EmailTemplate("html-only", "S", "t", ""), REGION);
EmailTemplate updated = service.getTemplate("html-only", REGION);
assertEquals("t", updated.getTextPart());
assertNull(updated.getHtmlPart());
}
// probed: a whitespace-only part beside a real one is kept as written
@Test
void whitespaceOnlyPartBesideARealOneIsKept() {
service.createTemplate(new EmailTemplate("blank-text", "S", " ", "<p>h</p>"), REGION, ACCOUNT);
assertEquals(" ", service.getTemplate("blank-text", REGION).getTextPart());
}
@Test
void create_rejectsBlankName() {
assertThrows(AwsException.class, () -> service.createTemplate(template(" "), REGION));
assertThrows(AwsException.class, () -> service.createTemplate(template(" "), REGION, ACCOUNT));
}
@Test
void create_rejectsEmptyBody() {
assertThrows(AwsException.class,
() -> service.createTemplate(new EmailTemplate("empty", null, null, null), REGION));
() -> service.createTemplate(new EmailTemplate("empty", null, null, null), REGION, ACCOUNT));
}
@Test
@@ -83,7 +168,7 @@ class SesTemplateServiceTest {
@Test
void update_preservesCreatedTimestamp_missingThrows() {
EmailTemplate created = service.createTemplate(template("welcome"), REGION);
EmailTemplate created = service.createTemplate(template("welcome"), REGION, ACCOUNT);
EmailTemplate update = template("welcome");
update.setSubject("Updated");
@@ -96,7 +181,7 @@ class SesTemplateServiceTest {
@Test
void delete_removesTemplate_missingThrows() {
service.createTemplate(template("welcome"), REGION);
service.createTemplate(template("welcome"), REGION, ACCOUNT);
service.deleteTemplate("welcome", REGION);
assertThrows(AwsException.class, () -> service.getTemplate("welcome", REGION));
assertThrows(AwsException.class, () -> service.deleteTemplate("welcome", REGION));
@@ -107,7 +192,7 @@ class SesTemplateServiceTest {
SesTemplateService ticking = new SesTemplateService(new InMemoryStorage<>(), new ObjectMapper(),
new SecureRandom(), new MutableClock());
Instant created = ticking.createTemplate(template("welcome"), REGION).getCreatedTimestamp();
Instant created = ticking.createTemplate(template("welcome"), REGION, ACCOUNT).getCreatedTimestamp();
ticking.updateTemplate(template("welcome"), REGION);
EmailTemplate stored = ticking.getTemplate("welcome", REGION);
@@ -120,9 +205,9 @@ class SesTemplateServiceTest {
SesTemplateService ticking = new SesTemplateService(new InMemoryStorage<>(), new ObjectMapper(),
new SecureRandom(), new MutableClock());
for (String name : List.of("a", "b", "c", "d", "e")) {
ticking.createTemplate(template(name), REGION);
ticking.createTemplate(template(name), REGION, ACCOUNT);
}
ticking.createTemplate(template("other"), "eu-west-1");
ticking.createTemplate(template("other"), "eu-west-1", ACCOUNT);
List<String> names = ticking.listTemplates(REGION).stream()
.map(EmailTemplate::getTemplateName).toList();
@@ -131,7 +216,7 @@ class SesTemplateServiceTest {
@Test
void findAndSave_supportFacadeTagging() {
service.createTemplate(template("welcome"), REGION);
service.createTemplate(template("welcome"), REGION, ACCOUNT);
assertTrue(service.find("ghost", REGION).isEmpty());
EmailTemplate found = service.find("welcome", REGION).orElseThrow();
@@ -146,7 +231,7 @@ class SesTemplateServiceTest {
@Test
void tagOps_lifecycle_notFoundMessage() {
service.createTemplate(template("welcome"), REGION);
service.createTemplate(template("welcome"), REGION, ACCOUNT);
service.tag("welcome", REGION, List.of(new Tag("team", "floci"), new Tag("env", "dev")));
assertEquals(2, service.listTags("welcome", REGION).size());
@@ -413,7 +498,7 @@ class SesTemplateServiceTest {
// probed: a whitespace-only text part beside an HTML part is still written as a part
@Test
void renderTestTemplate_whitespaceOnlyPartStaysAPart() {
service.createTemplate(new EmailTemplate("blank-text", "S", " ", "<p>x</p>"), REGION);
service.createTemplate(new EmailTemplate("blank-text", "S", " ", "<p>x</p>"), REGION, ACCOUNT);
String mime = service.renderTestTemplate("blank-text", "{}", REGION, "000000000000");
assertTrue(mime.contains("Content-Type: multipart/alternative; "));
assertTrue(mime.contains("Content-Type: text/plain; charset=UTF-8\r\n"
@@ -424,7 +509,7 @@ class SesTemplateServiceTest {
// probed: a part whose variables render to nothing, or to whitespace, is written empty
@Test
void renderTestTemplate_partRenderingToNothingStaysAPart() {
service.createTemplate(new EmailTemplate("empty-html", "S", "t", "{{h}}"), REGION);
service.createTemplate(new EmailTemplate("empty-html", "S", "t", "{{h}}"), REGION, ACCOUNT);
String empty = service.renderTestTemplate("empty-html", "{\"h\": \"\"}", REGION, "000000000000");
assertTrue(empty.contains("Content-Type: text/html; charset=UTF-8\r\n"
+ "Content-Transfer-Encoding: 7bit\r\n\r\n\r\n--"));
@@ -438,7 +523,7 @@ class SesTemplateServiceTest {
void renderTestTemplate_showsASampleUnsubscribeLink() {
service.createTemplate(new EmailTemplate("unsub", "U",
"u={{amazonSESUnsubscribeUrl}} t={{{amazonSESUnsubscribeUrl}}} s={{ amazonSESUnsubscribeUrl }}",
null), REGION);
null), REGION, ACCOUNT);
String mime = service.renderTestTemplate("unsub", "{}", REGION, "000000000000");
assertTrue(mime.endsWith("\r\n\r\nu=http://unsubscribe.example.com t=http://unsubscribe.example.com"
+ " s=http://unsubscribe.example.com"));
@@ -52,11 +52,14 @@ class SesTemplateV1IntegrationTest {
.formParam("Action", "CreateTemplate")
.formParam("Template.TemplateName", "v1-welcome")
.formParam("Template.SubjectPart", "dup")
.formParam("Template.TextPart", "dup")
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("<Code>AlreadyExists</Code>"));
.body(containsString("<Code>AlreadyExists</Code>"))
.body(containsString(
"<Message>Template v1-welcome already exists for account id 000000000000</Message>"));
}
@Test
@@ -69,7 +69,8 @@ class SesTemplateV2IntegrationTest {
.post("/v2/email/templates")
.then()
.statusCode(400)
.body("__type", equalTo("AlreadyExistsException"));
.body("__type", equalTo("AlreadyExistsException"))
.body("message", equalTo("Template v2-welcome already exists for account id 000000000000"));
}
@Test
@@ -155,7 +156,7 @@ class SesTemplateV2IntegrationTest {
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
.body("""
{"TemplateContent": {"Subject": "x"}}
{"TemplateContent": {"Subject": "x", "Text": "x"}}
""")
.when()
.put("/v2/email/templates/ghost")