From a8cb033a9895c2d16737b47ca53389a57eae154c Mon Sep 17 00:00:00 2001 From: Kenshin Okinaka Date: Fri, 20 Nov 2026 00:43:00 +0900 Subject: [PATCH] fix(ses): validate template names the way SES does (#8996) * fix(ses): validate template names the way SES does --- .../aws/services/ses/SesQueryHandler.java | 26 +- .../services/ses/SesTemplateController.java | 2 +- .../aws/services/ses/SesTemplateService.java | 31 ++- .../ses/SesTemplateNameIntegrationTest.java | 227 ++++++++++++++++++ .../services/ses/SesTemplateServiceTest.java | 89 ++++++- .../ses/SesTemplateV1IntegrationTest.java | 2 +- 6 files changed, 362 insertions(+), 15 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/ses/SesTemplateNameIntegrationTest.java diff --git a/src/main/java/io/floci/aws/services/ses/SesQueryHandler.java b/src/main/java/io/floci/aws/services/ses/SesQueryHandler.java index ec653a95a7..3c88824ec6 100644 --- a/src/main/java/io/floci/aws/services/ses/SesQueryHandler.java +++ b/src/main/java/io/floci/aws/services/ses/SesQueryHandler.java @@ -185,10 +185,31 @@ public class SesQueryHandler { "Operation " + action + " is not supported by SES.", AwsNamespaces.SES, 400); }; } catch (AwsException e) { - return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.SES, e.getHttpStatus()); + return AwsQueryResponse.error(e.getErrorCode(), spellOutControlCharacters(e.getMessage()), + AwsNamespaces.SES, e.getHttpStatus()); } } + /** + * SES writes a control character a message quotes as {@code 0x0009}, which also keeps the + * characters XML 1.0 forbids out of the error document. + */ + static String spellOutControlCharacters(String message) { + if (message == null || message.chars().noneMatch(c -> c < ' ')) { + return message; + } + StringBuilder out = new StringBuilder(message.length() + 8); + for (int i = 0; i < message.length(); i++) { + char c = message.charAt(i); + if (c < ' ') { + out.append(String.format(Locale.ROOT, "0x%04x", (int) c)); + } else { + out.append(c); + } + } + return out.toString(); + } + private Response handleVerifyEmailIdentity(MultivaluedMap params, String region) { String emailAddress = getParam(params, "EmailAddress"); identityService.verifyEmailIdentity(emailAddress, region); @@ -658,9 +679,6 @@ public class SesQueryHandler { private Response handleTestRenderTemplate(MultivaluedMap 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 = templateService.renderTestTemplate(templateName, templateDataRaw, region, regionResolver.getAccountId()); diff --git a/src/main/java/io/floci/aws/services/ses/SesTemplateController.java b/src/main/java/io/floci/aws/services/ses/SesTemplateController.java index 08e672a147..383842e294 100644 --- a/src/main/java/io/floci/aws/services/ses/SesTemplateController.java +++ b/src/main/java/io/floci/aws/services/ses/SesTemplateController.java @@ -66,7 +66,7 @@ public class SesTemplateController { try { JsonNode request = readOptionBody(objectMapper, body); String templateName = request.path("TemplateName").asText(null); - if (templateName == null || templateName.isBlank()) { + if (templateName == null || templateName.isEmpty()) { throw new AwsException("BadRequestException", "TemplateName is required.", 400); } EmailTemplate template = parseTemplateContent(templateName, request.path("TemplateContent")); diff --git a/src/main/java/io/floci/aws/services/ses/SesTemplateService.java b/src/main/java/io/floci/aws/services/ses/SesTemplateService.java index 8517127195..4103dab1a3 100644 --- a/src/main/java/io/floci/aws/services/ses/SesTemplateService.java +++ b/src/main/java/io/floci/aws/services/ses/SesTemplateService.java @@ -60,6 +60,8 @@ public class SesTemplateService implements SesTaggable { "\\{\\{\\{\\s*([\\w-]+)\\s*\\}\\}\\}|\\{\\{\\s*([\\w-]+)\\s*\\}\\}"); private static final DateTimeFormatter RENDER_DATE = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSX", Locale.ROOT).withZone(ZoneOffset.UTC); + private static final int MAX_TEMPLATE_NAME_LENGTH = 64; + private static final Pattern TEMPLATE_NAME = Pattern.compile("[A-Za-z0-9_-]+"); private static final Pattern SUBJECT_WHITESPACE_RUN = Pattern.compile("[ \\t\\r\\n]+"); static final String UNSUBSCRIBE_PLACEHOLDER = "{{amazonSESUnsubscribeUrl}}"; // What TestRenderTemplate shows in place of the list-management link a send would carry. @@ -102,13 +104,18 @@ public class SesTemplateService implements SesTaggable { } public EmailTemplate getTemplate(String templateName, String region) { + validateTemplateName(templateName); + return stored(templateName, region); + } + + private EmailTemplate stored(String templateName, String region) { return templateStore.get(templateKey(region, templateName)) .orElseThrow(() -> new AwsException("TemplateDoesNotExist", "Template " + templateName + " does not exist.", 400)); } EmailContent.InlineTemplate inline(EmailContent.Template template, String region) { - EmailTemplate stored = getTemplate(template.templateName(), region); + EmailTemplate stored = stored(template.templateName(), region); return new EmailContent.InlineTemplate(stored.getSubject(), stored.getTextPart(), stored.getHtmlPart(), template.templateData(), template.headers()); } @@ -131,6 +138,7 @@ public class SesTemplateService implements SesTaggable { } public void deleteTemplate(String templateName, String region) { + validateTemplateName(templateName); String key = templateKey(region, templateName); if (templateStore.get(key).isEmpty()) { throw new AwsException("TemplateDoesNotExist", @@ -203,19 +211,27 @@ public class SesTemplateService implements SesTaggable { } } + /** + * The name rules create, update, get, delete and test-render apply before anything else, in + * SES's order: blank, then longer than {@value #MAX_TEMPLATE_NAME_LENGTH}, then a character + * outside ASCII letters, digits, '_' and '-'. The sends, the tag operations and the tenant + * association read a template without them: what SES answers there for such a name is not known. + */ private static void validateTemplateName(String templateName) { if (templateName == null || templateName.isBlank()) { - throw new AwsException("InvalidTemplate", "TemplateName is required.", 400); + throw new AwsException("InvalidParameterValue", "The template name must be specified.", 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); + if (templateName.length() > MAX_TEMPLATE_NAME_LENGTH) { + throw new AwsException("InvalidParameterValue", + "Template name cannot exceed " + MAX_TEMPLATE_NAME_LENGTH + " characters.", 400); + } + if (!TEMPLATE_NAME.matcher(templateName).matches()) { + throw new AwsException("InvalidParameterValue", "Template name <" + templateName + + ">: only alphanumeric ASCII characters, '_', and '-' are allowed.", 400); } } private static String templateKey(String region, String templateName) { - validateTemplateName(templateName); return "template::" + region + "::" + templateName; } @@ -278,6 +294,7 @@ public class SesTemplateService implements SesTaggable { public String renderTestTemplate(String templateName, String templateDataRaw, String region, String accountId) { + validateTemplateName(templateName); // The rendering data is read before the template is looked up: both wrong answers the data error. JsonNode templateData = parseRenderingData(objectMapper, templateDataRaw); // TestRenderTemplate words a missing template its own way, unlike the template CRUD. diff --git a/src/test/java/io/floci/aws/services/ses/SesTemplateNameIntegrationTest.java b/src/test/java/io/floci/aws/services/ses/SesTemplateNameIntegrationTest.java new file mode 100644 index 0000000000..739bb12cea --- /dev/null +++ b/src/test/java/io/floci/aws/services/ses/SesTemplateNameIntegrationTest.java @@ -0,0 +1,227 @@ +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; + +/** + * The template name rules, as probed on us-west-2: blank, then longer than 64 characters, then a + * character outside ASCII letters, digits, '_' and '-'. Create, update, get, delete and test-render + * all answer them, on both APIs, before the name is looked up; the other lookups do not apply them. + */ +@QuarkusTest +class SesTemplateNameIntegrationTest { + + 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 BLANK = "The template name must be specified."; + private static final String TOO_LONG = "Template name cannot exceed 64 characters."; + + private static String notAllowed(String name) { + return "Template name <" + name + ">: only alphanumeric ASCII characters, '_', and '-' are allowed."; + } + + static Stream refusedNames() { + return Stream.of( + Arguments.of(" ", BLANK), + Arguments.of("a".repeat(65), TOO_LONG), + Arguments.of("name-probe ", notAllowed("name-probe ")), + Arguments.of(" name-probe", notAllowed(" name-probe")), + Arguments.of("name probe", notAllowed("name probe")), + Arguments.of("name.probe", notAllowed("name.probe")), + Arguments.of("name:probe", notAllowed("name:probe")), + Arguments.of("name-probé", notAllowed("name-probé"))); + } + + @ParameterizedTest + @MethodSource("refusedNames") + void v1_everyOperationRefusesTheName(String name, String message) { + for (String action : new String[] {"CreateTemplate", "UpdateTemplate"}) { + given() + .contentType("application/x-www-form-urlencoded; charset=UTF-8") + .header("Authorization", V1_AUTH) + .formParam("Action", action) + .formParam("Template.TemplateName", name) + .formParam("Template.SubjectPart", "S") + .formParam("Template.TextPart", "t") + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue")) + .body("ErrorResponse.Error.Message", equalTo(message)); + } + for (String action : new String[] {"GetTemplate", "DeleteTemplate", "TestRenderTemplate"}) { + given() + .contentType("application/x-www-form-urlencoded; charset=UTF-8") + .header("Authorization", V1_AUTH) + .formParam("Action", action) + .formParam("TemplateName", name) + .formParam("TemplateData", "{}") + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue")) + .body("ErrorResponse.Error.Message", equalTo(message)); + } + } + + @ParameterizedTest + @MethodSource("refusedNames") + void v2_everyOperationRefusesTheName(String name, String message) { + given() + .contentType("application/json; charset=UTF-8") + .header("Authorization", V2_AUTH) + .body("{\"TemplateName\": \"" + name + "\", \"TemplateContent\": {\"Subject\": \"S\", \"Text\": \"t\"}}") + .when() + .post("/v2/email/templates") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo(message)); + + given() + .contentType("application/json") + .header("Authorization", V2_AUTH) + .body("{\"TemplateContent\": {\"Subject\": \"S\", \"Text\": \"t\"}}") + .when() + .put("/v2/email/templates/{name}", name) + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo(message)); + + given() + .header("Authorization", V2_AUTH) + .when() + .get("/v2/email/templates/{name}", name) + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo(message)); + + given() + .header("Authorization", V2_AUTH) + .when() + .delete("/v2/email/templates/{name}", name) + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo(message)); + + given() + .contentType("application/json") + .header("Authorization", V2_AUTH) + .body("{\"TemplateData\": \"{}\"}") + .when() + .post("/v2/email/templates/{name}/render", name) + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo(message)); + } + + // probed: the name is checked before the subject + @Test + void theNameIsCheckedBeforeTheContent() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", V1_AUTH) + .formParam("Action", "CreateTemplate") + .formParam("Template.TemplateName", "name probe") + .formParam("Template.TextPart", "t") + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Message", equalTo(notAllowed("name probe"))); + + given() + .contentType("application/json") + .header("Authorization", V2_AUTH) + .body("{\"TemplateName\": \"name probe\", \"TemplateContent\": {\"Text\": \"t\"}}") + .when() + .post("/v2/email/templates") + .then() + .statusCode(400) + .body("message", equalTo(notAllowed("name probe"))); + } + + // probed: v1 writes a control character of the name as 0x0009, v2 sends it as it came + @Test + void v1SpellsOutAControlCharacterOfTheName() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", V1_AUTH) + .formParam("Action", "GetTemplate") + .formParam("TemplateName", "name\tprobe\u0001") + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Message", equalTo(notAllowed("name0x0009probe0x0001"))); + + given() + .contentType("application/json") + .header("Authorization", V2_AUTH) + .body("{\"TemplateName\": \"name\\tprobe\", \"TemplateContent\": {\"Subject\": \"S\", \"Text\": \"t\"}}") + .when() + .post("/v2/email/templates") + .then() + .statusCode(400) + .body("message", equalTo(notAllowed("name\tprobe"))); + } + + @Test + void a64CharacterNameOfEveryAllowedKindIsAccepted() { + String name = "Name_probe-0123456789" + "a".repeat(43); + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", V1_AUTH) + .formParam("Action", "CreateTemplate") + .formParam("Template.TemplateName", name) + .formParam("Template.SubjectPart", "S") + .formParam("Template.TextPart", "t") + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("Authorization", V2_AUTH) + .when() + .get("/v2/email/templates/{name}", name) + .then() + .statusCode(200) + .body("TemplateName", equalTo(name)); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", V1_AUTH) + .formParam("Action", "GetTemplate") + .formParam("TemplateName", name) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("" + name + "")); + + given() + .header("Authorization", V2_AUTH) + .when() + .delete("/v2/email/templates/{name}", name) + .then() + .statusCode(200); + } +} diff --git a/src/test/java/io/floci/aws/services/ses/SesTemplateServiceTest.java b/src/test/java/io/floci/aws/services/ses/SesTemplateServiceTest.java index abf663dccf..2aa96d1877 100644 --- a/src/test/java/io/floci/aws/services/ses/SesTemplateServiceTest.java +++ b/src/test/java/io/floci/aws/services/ses/SesTemplateServiceTest.java @@ -11,9 +11,11 @@ import io.floci.aws.services.ses.model.Tag; import io.floci.aws.testing.MutableClock; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import java.security.SecureRandom; import java.time.Clock; @@ -150,9 +152,92 @@ class SesTemplateServiceTest { assertEquals(" ", service.getTemplate("blank-text", REGION).getTextPart()); } + static Stream refusedNames() { + String charset = ">: only alphanumeric ASCII characters, '_', and '-' are allowed."; + return Stream.of( + Arguments.of(null, "The template name must be specified."), + Arguments.of("", "The template name must be specified."), + Arguments.of(" ", "The template name must be specified."), + Arguments.of("\t", "The template name must be specified."), + Arguments.of("\u3000", "The template name must be specified."), + Arguments.of("a".repeat(65), "Template name cannot exceed 64 characters."), + // probed: the length is checked before the characters + Arguments.of("a".repeat(64) + " ", "Template name cannot exceed 64 characters."), + Arguments.of("welcome ", "Template name operations = List.of( + () -> service.createTemplate(template(name), REGION, ACCOUNT), + () -> service.updateTemplate(template(name), REGION), + () -> service.getTemplate(name, REGION), + () -> service.deleteTemplate(name, REGION), + () -> service.renderTestTemplate(name, "{}", REGION, ACCOUNT)); + for (Executable operation : operations) { + AwsException e = assertThrows(AwsException.class, operation); + assertEquals("InvalidParameterValue", e.getErrorCode()); + assertEquals(message, e.getMessage()); + } + } + + // probed: the name is checked before the subject @Test - void create_rejectsBlankName() { - assertThrows(AwsException.class, () -> service.createTemplate(template(" "), REGION, ACCOUNT)); + void create_refusesTheNameBeforeTheContent() { + AwsException e = assertThrows(AwsException.class, + () -> service.createTemplate(new EmailTemplate("wel come", null, null, null), REGION, ACCOUNT)); + assertEquals("Template name : only alphanumeric ASCII characters, '_', and '-' are allowed.", + e.getMessage()); + } + + @ParameterizedTest + @ValueSource(strings = {"-", "_", "0123456789", "Welcome_Mail-2"}) + void create_acceptsLettersDigitsUnderscoreAndHyphen(String name) { + service.createTemplate(template(name), REGION, ACCOUNT); + assertEquals(name, service.getTemplate(name, REGION).getTemplateName()); + } + + // The sends, the tag operations and the tenant association were not probed with such a name: + // they keep answering that the template is missing. + @ParameterizedTest + @ValueSource(strings = {"wel.come", "wel come", " welcome"}) + void lookupsOutsideTheTemplateOperations_treatARefusedNameAsMissing(String name) { + assertTrue(service.find(name, REGION).isEmpty()); + + AwsException tags = assertThrows(AwsException.class, () -> service.listTags(name, REGION)); + assertEquals("NotFoundException", tags.getErrorCode()); + assertEquals("No Template present with name: " + name, tags.getMessage()); + + EmailContent.Template content = new EmailContent.Template(name, MAPPER.createObjectNode(), List.of()); + AwsException send = assertThrows(AwsException.class, () -> service.inline(content, REGION)); + assertEquals("TemplateDoesNotExist", send.getErrorCode()); + assertEquals("Template " + name + " does not exist.", send.getMessage()); + } + + // probed with an unknown name and bad data; the name rules come ahead of both + @Test + void renderTestTemplate_refusesTheNameBeforeTheData() { + AwsException e = assertThrows(AwsException.class, + () -> service.renderTestTemplate("wel come", null, REGION, ACCOUNT)); + assertEquals("InvalidParameterValue", e.getErrorCode()); + } + + @Test + void create_acceptsA64CharacterName() { + String name = "a".repeat(64); + service.createTemplate(template(name), REGION, ACCOUNT); + assertEquals(name, service.getTemplate(name, REGION).getTemplateName()); } @Test diff --git a/src/test/java/io/floci/aws/services/ses/SesTemplateV1IntegrationTest.java b/src/test/java/io/floci/aws/services/ses/SesTemplateV1IntegrationTest.java index 3dcb17db63..8036e29d46 100644 --- a/src/test/java/io/floci/aws/services/ses/SesTemplateV1IntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ses/SesTemplateV1IntegrationTest.java @@ -279,7 +279,7 @@ class SesTemplateV1IntegrationTest { .post("/") .then() .statusCode(400) - .body(containsString("InvalidTemplate")); + .body(containsString("InvalidParameterValue")); } @Test