fix(ses): enforce full AWS tag validation across all SES resources (#2504)

* fix(ses): enforce full AWS tag validation across all SES resources

The shared SES tag validator only checked a single tag's key/value
length, so CreateConfigurationSet, CreateEmailTemplate,
CreateEmailIdentity, CreateContactList, TagResource, and tenant tagging
all silently accepted invalid tag sets.

Add SesTags.validate(List<Tag>) matching probe-confirmed AWS SES v2
behavior: at most 50 tags, unique keys, key 1-128 / value 0-256 code
points, both key and value restricted to letters, numbers, Unicode
whitespace, and _ . : / = + - @, and the aws: key prefix
(case-insensitive) reserved for system tags. Lengths are counted by
Unicode code point (Smithy semantics), not UTF-16 code units.
TagResource enforces the 50-tag limit on the merged (existing +
incoming) set, allowing updates to existing keys. Messages and
evaluation order mirror AWS; all violations are BadRequestException / 400.

Route every SES tag entry point through the validator, and validate
CreateEmailIdentity's tags before the identity is persisted so an
invalid tag set fails atomically instead of leaving the identity behind.
Update the integration tests that encoded the old non-AWS behavior (an
omitted tag value now returns 400 like real AWS).

* test(ses): cover CreateEmailTemplate invalid-tag rejection

Route-level coverage that CreateEmailTemplate rejects an invalid tag set
(duplicate keys) atomically without persisting the template. The
service-level SesTags call was otherwise only exercised through
SesTagsTest, so a regression removing it could pass unnoticed.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-08-25 22:47:58 -05:00
1 parent 55edfd9412
commit 29f6e7ac6b
11 files changed
+480 -42

No files matched your search

@@ -275,7 +275,7 @@ class SesConfigurationSetV2IntegrationTest {
@Test
@Order(12)
void createConfigurationSet_tagWithMissingValue_roundTripsAsAbsent() {
void createConfigurationSet_tagWithMissingValue_returns400() {
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
@@ -288,15 +288,10 @@ class SesConfigurationSetV2IntegrationTest {
.when()
.post("/v2/email/configuration-sets")
.then()
.statusCode(200);
given()
.header("Authorization", AUTH_HEADER)
.when()
.get("/v2/email/configuration-sets/v2-cs-tag-no-value")
.then()
.statusCode(200)
.body("Tags[0].Key", equalTo("env"));
.statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("Tags can only contain letters, numbers, spaces, and the "
+ "following special characters: _ . : / = + - @"));
}
@Test
@@ -429,6 +429,17 @@ class SesContactListV2IntegrationTest {
+ "Member must satisfy enum value set: [OPT_OUT, OPT_IN]"));
}
@Test
@Order(25)
void createContactList_duplicateTagKeys_returns400() {
post("{\"ContactListName\":\"tagged-list\",\"Topics\":[],"
+ "\"Tags\":[{\"Key\":\"dup\",\"Value\":\"1\"},{\"Key\":\"dup\",\"Value\":\"2\"}]}")
.then()
.statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("Cannot provide multiple tags with the same key"));
}
private static io.restassured.response.Response post(String body) {
return given()
.contentType("application/json")
@@ -0,0 +1,202 @@
package io.github.hectorvent.floci.services.ses;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.ses.model.Tag;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* Unit test for the shared SES tag validation. Rules and messages are probe-confirmed against real AWS
* SES v2 (2026-08-23): max 50 tags, unique keys, key 1–128 / value 0–256 chars, and a restricted
* character set on both key and value.
*/
class SesTagsTest {
private static Tag tag(String k, String v) {
return new Tag(k, v);
}
@Test
void validList_and_emptyOrNull_ok() {
assertDoesNotThrow(() -> SesTags.validate((List<Tag>) null));
assertDoesNotThrow(() -> SesTags.validate(List.of()));
assertDoesNotThrow(() -> SesTags.validate(List.of(tag("env", "dev"), tag("owner", "alice"))));
// Empty value and the allowed special characters are accepted.
assertDoesNotThrow(() -> SesTags.validate(List.of(tag("k", ""))));
assertDoesNotThrow(() -> SesTags.validate(List.of(tag("k", "_ . : / = + - @ a1"))));
}
@Test
void tooManyTags_reportsMaxFifty() {
List<Tag> tags = new ArrayList<>();
for (int i = 0; i < 51; i++) {
tags.add(tag("k" + i, "v"));
}
AwsException e = assertThrows(AwsException.class, () -> SesTags.validate(tags));
assertEquals("BadRequestException", e.getErrorCode());
assertEquals("Maximum of 50 user tags are allowed per resource, consider reducing the number "
+ "of tags in the request", e.getMessage());
}
@Test
void fiftyTags_ok() {
List<Tag> tags = new ArrayList<>();
for (int i = 0; i < 50; i++) {
tags.add(tag("k" + i, "v"));
}
assertDoesNotThrow(() -> SesTags.validate(tags));
}
@Test
void duplicateKeys_rejected() {
AwsException e = assertThrows(AwsException.class,
() -> SesTags.validate(List.of(tag("dup", "1"), tag("dup", "2"))));
assertEquals("Cannot provide multiple tags with the same key", e.getMessage());
}
@Test
void nullValue_isCharsetViolation() {
AwsException e = assertThrows(AwsException.class, () -> SesTags.validate(List.of(tag("k", null))));
assertEquals("Tags can only contain letters, numbers, spaces, and the following special "
+ "characters: _ . : / = + - @", e.getMessage());
}
@Test
void invalidChar_inValueOrKey_isCharsetViolation() {
String msg = "Tags can only contain letters, numbers, spaces, and the following special "
+ "characters: _ . : / = + - @";
assertEquals(msg, assertThrows(AwsException.class,
() -> SesTags.validate(List.of(tag("k", "bad!value")))).getMessage());
assertEquals(msg, assertThrows(AwsException.class,
() -> SesTags.validate(List.of(tag("bad!key", "v")))).getMessage());
}
@Test
void keyTooLong_smithyLengthMessage() {
AwsException e = assertThrows(AwsException.class,
() -> SesTags.validate(List.of(tag("k".repeat(129), "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", e.getMessage());
}
@Test
void valueTooLong_smithyLengthMessage() {
AwsException e = assertThrows(AwsException.class,
() -> SesTags.validate(List.of(tag("k", "v".repeat(257)))));
assertEquals("1 validation error detected: Value at 'tags.1.member.value' failed to satisfy "
+ "constraint: Member must have length less than or equal to 256", e.getMessage());
}
@Test
void multipleLengthViolations_aggregatedValueThenKey() {
AwsException e = assertThrows(AwsException.class,
() -> SesTags.validate(List.of(tag("k".repeat(129), "v".repeat(257)))));
assertEquals("2 validation errors detected: Value at 'tags.1.member.value' failed to satisfy "
+ "constraint: Member must have length less than or equal to 256; Value at "
+ "'tags.1.member.key' failed to satisfy constraint: Member must have length less than "
+ "or equal to 128", e.getMessage());
}
@Test
void charsetBeatsLength() {
// key too long AND value has an invalid char -> the character-set error wins (probe-confirmed).
AwsException e = assertThrows(AwsException.class,
() -> SesTags.validate(List.of(tag("k".repeat(129), "bad!"))));
assertEquals("Tags can only contain letters, numbers, spaces, and the following special "
+ "characters: _ . : / = + - @", e.getMessage());
}
@Test
void maxCountBeatsDuplicate() {
List<Tag> tags = new ArrayList<>();
tags.add(tag("dup", "1"));
tags.add(tag("dup", "2"));
for (int i = 0; i < 49; i++) {
tags.add(tag("k" + i, "v"));
}
AwsException e = assertThrows(AwsException.class, () -> SesTags.validate(tags));
assertEquals("Maximum of 50 user tags are allowed per resource, consider reducing the number "
+ "of tags in the request", e.getMessage());
}
@Test
void emptyKey_rejectedWithNullMessage() {
AwsException e = assertThrows(AwsException.class, () -> SesTags.validate(List.of(tag("", "v"))));
assertEquals("BadRequestException", e.getErrorCode());
assertNull(e.getMessage());
}
@Test
void awsPrefixKey_rejectedAsSystemTag() {
AwsException e = assertThrows(AwsException.class,
() -> SesTags.validate(List.of(tag("aws:foo", "v"))));
assertEquals("BadRequestException", e.getErrorCode());
assertEquals("Caller is an end user and not allowed to mutate system tags", e.getMessage());
}
@Test
void awsPrefixKey_isCaseInsensitive() {
AwsException e = assertThrows(AwsException.class,
() -> SesTags.validate(List.of(tag("AWS:foo", "v"))));
assertEquals("Caller is an end user and not allowed to mutate system tags", e.getMessage());
}
@Test
void awsPrefix_onlyAppliesToKey_valueAndNoColonAreAllowed() {
// A value starting with aws: is allowed; only a key with the reserved prefix is rejected.
assertDoesNotThrow(() -> SesTags.validate(List.of(tag("k", "aws:foo"))));
// "aws" / "awsfoo" without the colon are ordinary keys.
assertDoesNotThrow(() -> SesTags.validate(List.of(tag("aws", "v"))));
assertDoesNotThrow(() -> SesTags.validate(List.of(tag("awsfoo", "v"))));
}
@Test
void charsetBeatsAwsPrefix() {
// aws: reserved key AND an invalid char in the value -> the character-set error wins.
AwsException e = assertThrows(AwsException.class,
() -> SesTags.validate(List.of(tag("aws:foo", "bad!"))));
assertEquals("Tags can only contain letters, numbers, spaces, and the following special "
+ "characters: _ . : / = + - @", e.getMessage());
}
@Test
void validateMergedCount_overFifty_usesMergeMessage() {
AwsException e = assertThrows(AwsException.class, () -> SesTags.validateMergedCount(51));
assertEquals("BadRequestException", e.getErrorCode());
assertEquals("Maximum of 50 user tags are allowed per resource, consider reducing the number "
+ "of tags in the request or delete existing tags and retry", e.getMessage());
}
@Test
void validateMergedCount_fiftyOrFewer_ok() {
assertDoesNotThrow(() -> SesTags.validateMergedCount(50));
assertDoesNotThrow(() -> SesTags.validateMergedCount(0));
}
@Test
void unicodeWhitespace_isAllowed() {
// U+00A0 (no-break space) is a Unicode separator (\p{Z}), not the ASCII space. AWS accepts it
// in both key and value (probe-confirmed), so the charset rule must allow it.
assertDoesNotThrow(() -> SesTags.validate(List.of(tag("a\u00A0b", "c\u00A0d"))));
}
@Test
void length_countsUnicodeCodePointsNotUtf16Units() {
// U+1D400 (MATHEMATICAL BOLD CAPITAL A) is a letter (\p{L}, charset-allowed) that occupies one
// code point but two UTF-16 code units. Smithy length constraints count code points, so 128 of
// them is exactly the key limit (would be 256 UTF-16 units).
String cp = "\uD835\uDC00";
assertDoesNotThrow(() -> SesTags.validate(List.of(tag(cp.repeat(128), "v"))));
AwsException e = assertThrows(AwsException.class,
() -> SesTags.validate(List.of(tag(cp.repeat(129), "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", e.getMessage());
}
}
@@ -530,4 +530,115 @@ class SesTagsV2IntegrationTest {
.body("Tags[0].Key", equalTo("owner"))
.body("Tags[0].Value", equalTo("alice"));
}
@Test
@Order(20)
void tagResource_mergeExceedingFifty_returns400() {
// AWS enforces the 50-tag ceiling on the MERGED (existing + incoming) set, and updating an
// existing key (net count unchanged) is allowed. Probe-confirmed against real AWS.
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
.body("""
{"ConfigurationSetName": "tag-cs-merge"}
""")
.when()
.post("/v2/email/configuration-sets")
.then()
.statusCode(200);
String arn = "arn:aws:ses:us-east-1:000000000000:configuration-set/tag-cs-merge";
// Seed with the full 50 tags.
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
.body("{\"ResourceArn\": \"" + arn + "\", \"Tags\": " + tagArray(0, 50) + "}")
.when()
.post("/v2/email/tags")
.then()
.statusCode(200);
// Updating an existing key keeps the count at 50 and is accepted.
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
.body("{\"ResourceArn\": \"" + arn + "\", \"Tags\": [{\"Key\": \"k0\", \"Value\": \"updated\"}]}")
.when()
.post("/v2/email/tags")
.then()
.statusCode(200);
// Adding one new key would make 51 — rejected with the merge-specific message.
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
.body("{\"ResourceArn\": \"" + arn + "\", \"Tags\": [{\"Key\": \"extra\", \"Value\": \"v\"}]}")
.when()
.post("/v2/email/tags")
.then()
.statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("Maximum of 50 user tags are allowed per resource, consider "
+ "reducing the number of tags in the request or delete existing tags and retry"));
}
@Test
@Order(21)
void tagResource_reservedAwsPrefixKey_returns400() {
String arn = "arn:aws:ses:us-east-1:000000000000:configuration-set/tag-cs-1";
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
.body("{\"ResourceArn\": \"" + arn + "\", \"Tags\": [{\"Key\": \"aws:foo\", \"Value\": \"v\"}]}")
.when()
.post("/v2/email/tags")
.then()
.statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("Caller is an end user and not allowed to mutate system tags"));
}
@Test
@Order(22)
void createEmailIdentity_invalidInlineTags_isAtomic_identityNotPersisted() {
// A semantic tag error must fail CreateEmailIdentity before the identity is persisted, so a
// corrected retry does not hit AlreadyExistsException. Validation is now applied to the parsed
// tag list up front, before verifyEmailIdentity/verifyDomainIdentity.
String id = "atomic-tag-id@example.com";
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
.body("""
{"EmailIdentity": "%s", "Tags": [
{"Key": "dup", "Value": "1"},
{"Key": "dup", "Value": "2"}
]}
""".formatted(id))
.when()
.post("/v2/email/identities")
.then()
.statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("Cannot provide multiple tags with the same key"));
// The failed create must leave no identity behind.
given()
.header("Authorization", AUTH_HEADER)
.when()
.get("/v2/email/identities/" + id)
.then()
.statusCode(404);
}
private static String tagArray(int from, int to) {
StringBuilder sb = new StringBuilder("[");
for (int i = from; i < to; i++) {
if (i > from) {
sb.append(",");
}
sb.append("{\"Key\": \"k").append(i).append("\", \"Value\": \"v\"}");
}
return sb.append("]").toString();
}
}
@@ -633,6 +633,37 @@ class SesTemplateV2IntegrationTest {
.body("Tags.find { it.Key == 'team' }.Value", equalTo("platform"));
}
@Test
@Order(24)
void createTemplate_invalidTags_returns400_andNotPersisted() {
// Route-level coverage: CreateEmailTemplate must reject an invalid tag set (here duplicate
// keys) atomically, before the template is persisted.
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
.body("""
{
"TemplateName": "v2-badtags",
"TemplateContent": {"Subject": "S", "Text": "T"},
"Tags": [{"Key": "dup", "Value": "1"}, {"Key": "dup", "Value": "2"}]
}
""")
.when()
.post("/v2/email/templates")
.then()
.statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("Cannot provide multiple tags with the same key"));
// The failed create must leave no template behind.
given()
.header("Authorization", AUTH_HEADER)
.when()
.get("/v2/email/templates/v2-badtags")
.then()
.statusCode(404);
}
@ParameterizedTest(name = "{0}")
@MethodSource("malformedSendEmailBodies")
@Order(50)