fix(ses): check a template's tags before its name and content (#9041)

CreateEmailTemplate validated the tags last, after the template name
and content. SES checks them first, as probed on us-west-2: the tag
count, character set, lengths, an empty key and duplicate keys are all
refused ahead of a blank name or a missing subject or part.

The reserved aws: key prefix is the exception. SES refuses it after
the name and the content, before it looks the name up, and words it
"Invalid tags" on this operation.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-11-19 19:24:53 -04:00
1 parent f08cc57437
commit c91740de85
5 files changed
+225 -10

No files matched your search

@@ -52,9 +52,45 @@ final class SesTags {
* prefix reserved. A {@code null}/empty list is a no-op.
*/
static void validate(List<Tag> tags) {
validate(tags, true);
}
/**
* {@link #validate} without the reserved {@code aws:} prefix, for an operation that refuses such
* a key at another point and in its own words (see {@link #requireNoSystemKeys}).
*/
static void validateIgnoringSystemKeys(List<Tag> tags) {
validate(tags, false);
}
private static void validate(List<Tag> tags, boolean refuseSystemKeys) {
if (tags == null || tags.isEmpty()) {
return;
}
requireCountAndCharset(tags);
// The aws: key prefix is checked after the character set (probe-confirmed).
if (refuseSystemKeys) {
requireNoSystemKeys(tags, SYSTEM_TAG_MESSAGE);
}
requireLengthsAndDistinctKeys(tags);
}
/**
* Refuses a key with the reserved {@code aws:} prefix (case-insensitive). Only the key is checked,
* a value starting with {@code aws:} is allowed.
*/
static void requireNoSystemKeys(List<Tag> tags, String message) {
if (tags == null) {
return;
}
for (Tag tag : tags) {
if (tag != null && tag.key() != null && tag.key().regionMatches(true, 0, "aws:", 0, 4)) {
throw new AwsException("BadRequestException", message, 400);
}
}
}
private static void requireCountAndCharset(List<Tag> tags) {
if (tags.size() > MAX_TAGS) {
throw new AwsException("BadRequestException", MAX_TAGS_MESSAGE, 400);
}
@@ -64,13 +100,9 @@ final class SesTags {
throw new AwsException("BadRequestException", CHARSET_MESSAGE, 400);
}
}
// The aws: key prefix (case-insensitive) is reserved for system tags; only the key is checked
// — a value starting with aws: is allowed. Checked after the character set (probe-confirmed).
for (Tag tag : tags) {
if (tag.key() != null && tag.key().regionMatches(true, 0, "aws:", 0, 4)) {
throw new AwsException("BadRequestException", SYSTEM_TAG_MESSAGE, 400);
}
}
}
private static void requireLengthsAndDistinctKeys(List<Tag> tags) {
// Length violations are reported together in the AWS Smithy form, value before key, with a
// 1-based tag index. Smithy length constraints count Unicode code points, not UTF-16 code
// units, so a supplementary-plane character counts as one.
@@ -47,7 +47,7 @@ import java.util.regex.Pattern;
* {@link SecureRandom} (no static instance, so no native-image run-time-init registration).
*
* <p>Tag validation is a shared cross-resource concern, so {@code createTemplate} calls
* {@link SesTags#validate} rather than depending back on the facade.
* {@link SesTags} rather than depending back on the facade.
*/
@ApplicationScoped
public class SesTemplateService implements SesTaggable {
@@ -85,9 +85,13 @@ public class SesTemplateService implements SesTaggable {
}
public EmailTemplate createTemplate(EmailTemplate template, String region, String accountId) {
requirePresent(template);
// SES checks the tags before the template itself, except for a reserved key, which it
// refuses after the template, before it looks the name up, and in words of its own.
SesTags.validateIgnoringSystemKeys(template.getTags());
validateTemplate(template);
dropEmptyParts(template);
SesTags.validate(template.getTags());
SesTags.requireNoSystemKeys(template.getTags(), "Invalid tags");
String key = templateKey(region, template.getTemplateName());
if (templateStore.get(key).isPresent()) {
throw new AwsException("AlreadyExists",
@@ -179,10 +183,14 @@ public class SesTemplateService implements SesTaggable {
templateStore.put(templateKey(region, template.getTemplateName()), template);
}
private static void validateTemplate(EmailTemplate template) {
private static void requirePresent(EmailTemplate template) {
if (template == null) {
throw new AwsException("InvalidTemplate", "Template is required.", 400);
}
}
private static void validateTemplate(EmailTemplate template) {
requirePresent(template);
validateTemplateName(template.getTemplateName());
// SES asks for the subject first, then for a part, and a blank value counts as missing.
if (template.getSubject() == null || template.getSubject().isBlank()) {
@@ -78,6 +78,35 @@ class SesTagsTest {
() -> SesTags.validate(List.of(tag("bad!key", "v")))).getMessage());
}
// probed: CreateEmailTemplate checks everything but the aws: prefix ahead of the template
@Test
void validateIgnoringSystemKeys_leavesTheReservedPrefixAlone() {
assertDoesNotThrow(() -> SesTags.validateIgnoringSystemKeys(null));
assertDoesNotThrow(() -> SesTags.validateIgnoringSystemKeys(List.of(tag("aws:x", "v"))));
assertEquals("Cannot provide multiple tags with the same key", assertThrows(AwsException.class,
() -> SesTags.validateIgnoringSystemKeys(List.of(tag("aws:x", "a"), tag("aws:x", "b")))).getMessage());
AwsException tooLong = assertThrows(AwsException.class,
() -> SesTags.validateIgnoringSystemKeys(List.of(tag("aws:" + "k".repeat(125), "v"))));
assertEquals("1 validation error detected: Value at 'tags.1.member.key' failed to satisfy "
+ "constraint: Member must have length less than or equal to 128", tooLong.getMessage());
// the character set still comes before the length
assertEquals("Tags can only contain letters, numbers, spaces, and the following special characters: "
+ "_ . : / = + - @", assertThrows(AwsException.class,
() -> SesTags.validateIgnoringSystemKeys(List.of(tag("!" + "k".repeat(128), "v")))).getMessage());
}
@Test
void requireNoSystemKeys_refusesTheReservedPrefixInTheGivenWords() {
assertDoesNotThrow(() -> SesTags.requireNoSystemKeys(null, "Invalid tags"));
assertDoesNotThrow(() -> SesTags.requireNoSystemKeys(List.of(tag("k", "aws:v")), "Invalid tags"));
for (String key : List.of("aws:x", "AWS:x")) {
AwsException e = assertThrows(AwsException.class,
() -> SesTags.requireNoSystemKeys(List.of(tag(key, "v")), "Invalid tags"));
assertEquals("BadRequestException", e.getErrorCode());
assertEquals("Invalid tags", e.getMessage());
}
}
@Test
void keyTooLong_smithyLengthMessage() {
AwsException e = assertThrows(AwsException.class,
@@ -122,6 +122,54 @@ class SesTemplateServiceTest {
Arguments.of(" ", ""));
}
private static EmailTemplate tagged(String name, String subject, String text, String tagKey) {
EmailTemplate template = new EmailTemplate(name, subject, text, null);
template.setTags(List.of(new Tag(tagKey, "v")));
return template;
}
// probed: a malformed tag is refused before the name and the content
@Test
void create_checksTagsBeforeTheNameAndTheContent() {
AwsException e = assertThrows(AwsException.class,
() -> service.createTemplate(tagged(" ", null, null, "bad!key"), REGION, ACCOUNT));
assertEquals("Tags can only contain letters, numbers, spaces, and the following special characters: "
+ "_ . : / = + - @", e.getMessage());
}
// probed: a reserved key waits for the content
@Test
void create_checksTheContentBeforeAReservedTagKey() {
AwsException e = assertThrows(AwsException.class,
() -> service.createTemplate(tagged("reserved", "S", null, "aws:x"), REGION, ACCOUNT));
assertEquals("Template must specify at least one of the parts.", e.getMessage());
}
// probed: the template operation words a reserved key its own way and stores nothing
@Test
void create_refusesAReservedTagKeyAsInvalidTags() {
AwsException e = assertThrows(AwsException.class,
() -> service.createTemplate(tagged("reserved", "S", "t", "aws:x"), REGION, ACCOUNT));
assertEquals("BadRequestException", e.getErrorCode());
assertEquals("Invalid tags", e.getMessage());
assertTrue(service.find("reserved", REGION).isEmpty());
}
// probed: a reserved key is refused before the name is looked up
@Test
void create_refusesAReservedTagKeyBeforeAnExistingName() {
service.createTemplate(template("stored"), REGION, ACCOUNT);
AwsException e = assertThrows(AwsException.class,
() -> service.createTemplate(tagged("stored", "S", "t", "aws:x"), REGION, ACCOUNT));
assertEquals("Invalid tags", e.getMessage());
}
@Test
void create_refusesANullTemplate() {
AwsException e = assertThrows(AwsException.class, () -> service.createTemplate(null, REGION, ACCOUNT));
assertEquals("Template is required.", e.getMessage());
}
// probed: the content is checked before the name is looked up, on both operations
@Test
void contentIsCheckedBeforeTheTemplateIsLookedUp() {
@@ -0,0 +1,98 @@
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.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
/**
* Where CreateEmailTemplate checks its tags, as probed on us-west-2: a malformed tag is refused before
* the template name and content, a reserved {@code aws:} key only after them and as "Invalid tags".
*/
@QuarkusTest
class SesTemplateTagOrderIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request";
private static final String SUBJECT_ONLY = "{\"Subject\": \"S\"}";
private static final String VALID = "{\"Subject\": \"S\", \"Text\": \"t\"}";
private static final String CHARSET = "Tags can only contain letters, numbers, spaces, and the following "
+ "special characters: _ . : / = + - @";
private static final String KEY_TOO_LONG = "1 validation error detected: Value at 'tags.1.member.key' "
+ "failed to satisfy constraint: Member must have length less than or equal to 128";
private static final String TOO_MANY = "Maximum of 50 user tags are allowed per resource, consider "
+ "reducing the number of tags in the request";
private static String tag(String key) {
return "{\"Key\": \"" + key + "\", \"Value\": \"v\"}";
}
static Stream<Arguments> refused() {
String fiftyOne = IntStream.range(0, 51).mapToObj(i -> tag("k" + i)).collect(Collectors.joining(", "));
return Stream.of(
// a malformed tag wins over a subject-only content and over a blank name
Arguments.of("tag-order", SUBJECT_ONLY, tag("k".repeat(129)), KEY_TOO_LONG),
Arguments.of("tag-order", "{\"Text\": \"t\"}", tag("a!b"), CHARSET),
Arguments.of("tag-order", SUBJECT_ONLY, fiftyOne, TOO_MANY),
Arguments.of("tag-order", SUBJECT_ONLY, tag("dup") + ", " + tag("dup"),
"Cannot provide multiple tags with the same key"),
Arguments.of("tag-order", SUBJECT_ONLY, tag(""), null),
Arguments.of(" ", VALID, tag("k".repeat(129)), KEY_TOO_LONG),
Arguments.of(" ", VALID, tag("a!b"), CHARSET),
// the length is reported for a reserved key too
Arguments.of("tag-order", VALID, tag("aws:" + "k".repeat(125)), KEY_TOO_LONG),
// a reserved key waits for the content
Arguments.of("tag-order", SUBJECT_ONLY, tag("aws:x"),
"Template must specify at least one of the parts."),
Arguments.of("tag-order", VALID, tag("aws:x"), "Invalid tags"),
Arguments.of("tag-order", VALID, tag("AWS:x"), "Invalid tags"));
}
@ParameterizedTest
@MethodSource("refused")
void create_refusesInTheOrderSesDoes(String name, String content, String tags, String message) {
given()
.contentType("application/json")
.header("Authorization", AUTH)
.body(createBody(name, content, tags))
.when()
.post("/v2/email/templates")
.then()
.statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo(message));
}
@Test
void create_refusedForAReservedKeyStoresNothing() {
given()
.contentType("application/json")
.header("Authorization", AUTH)
.body(createBody("tag-order-reserved", VALID, tag("aws:x")))
.when()
.post("/v2/email/templates")
.then()
.statusCode(400)
.body("message", equalTo("Invalid tags"));
given()
.header("Authorization", AUTH)
.when()
.get("/v2/email/templates/tag-order-reserved")
.then()
.statusCode(404);
}
private static String createBody(String name, String content, String tags) {
return "{\"TemplateName\": \"" + name + "\", \"TemplateContent\": " + content
+ ", \"Tags\": [" + tags + "]}";
}
}