Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

refactor(ses): extract the shared v2 JSON helpers and guard controller registration (#3640)

Kenshin Okinaka190c55694058
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java
index f84488cdfe..280d0ee88c 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java
@@ -55,6 +55,19 @@ import java.util.Collections;
import java.util.List;
import java.util.Map;
+import static io.github.hectorvent.floci.services.ses.SesV2Json.coerceBoolean;
+import static io.github.hectorvent.floci.services.ses.SesV2Json.intMemberOrAbsent;
+import static io.github.hectorvent.floci.services.ses.SesV2Json.parseOptionString;
+import static io.github.hectorvent.floci.services.ses.SesV2Json.parseTagsArray;
+import static io.github.hectorvent.floci.services.ses.SesV2Json.readOptionBody;
+import static io.github.hectorvent.floci.services.ses.SesV2Json.readRequiredStringField;
+import static io.github.hectorvent.floci.services.ses.SesV2Json.remapV1Exception;
+import static io.github.hectorvent.floci.services.ses.SesV2Json.requireJsonObject;
+import static io.github.hectorvent.floci.services.ses.SesV2Json.requireObjectOrAbsent;
+import static io.github.hectorvent.floci.services.ses.SesV2Json.stringArrayOrAbsent;
+import static io.github.hectorvent.floci.services.ses.SesV2Json.stringMemberOrAbsent;
+import static io.github.hectorvent.floci.services.ses.SesV2Json.unexpectedStartError;
+
/**
* REST JSON controller for the AWS SES V2 API.
* Implements the AWS SES V2 wire protocol at /v2/email/* for the operations
@@ -1110,19 +1123,6 @@ public class SesController {
}
}
- // Read a typed string member: absent/null returns null, but a present value of the wrong JSON type
- // is rejected rather than coerced (asText would turn 123 into "123"), matching AWS.
- private static String stringMemberOrAbsent(JsonNode parent, String field) {
- JsonNode n = parent.path(field);
- if (n.isMissingNode() || n.isNull()) {
- return null;
- }
- if (!n.isTextual()) {
- throw new AwsException("SerializationException", null, 400);
- }
- return n.textValue();
- }
-
private ObjectNode tenantJson(Tenant tenant) {
ObjectNode node = objectMapper.createObjectNode();
node.put("TenantName", tenant.tenantName());
@@ -1154,27 +1154,6 @@ public class SesController {
return node;
}
- // Parse an optional array of strings: absent/null returns null, an empty array stays an empty
- // list (the distinction matters for the suppression-attributes pair rules), and a non-string
- // element is rejected rather than coerced.
- private static List<String> stringArrayOrAbsent(JsonNode parent, String field) {
- JsonNode n = parent.path(field);
- if (n.isMissingNode() || n.isNull()) {
- return null;
- }
- if (!n.isArray()) {
- throw new AwsException("SerializationException", null, 400);
- }
- List<String> values = new ArrayList<>();
- for (JsonNode item : n) {
- if (!item.isTextual()) {
- throw new AwsException("SerializationException", null, 400);
- }
- values.add(item.textValue());
- }
- return values;
- }
-
@POST
@Path("/templates")
public Response createEmailTemplate(@Context HttpHeaders headers, String body) {
@@ -1459,7 +1438,8 @@ public class SesController {
// Reuse the AWS-aligned SendingEnabled deserialization shared with CreateConfigurationSet:
// absent -> false, string -> true, null/number -> SerializationException. An empty body
// / {} therefore disables sending (200). Verified against real AWS.
- boolean enabled = parseSendingEnabled(readOptionBody(body).path("SendingEnabled"));
+ boolean enabled = parseSendingEnabled(
+ readOptionBody(objectMapper, body).path("SendingEnabled"));
sesService.setConfigurationSetSendingEnabled(name, enabled, region);
LOG.infov("SES V2 PutConfigurationSetSendingOptions: {0} on {1}", enabled, name);
return Response.ok(objectMapper.createObjectNode()).build();
@@ -1475,7 +1455,7 @@ public class SesController {
String body) {
String region = regionResolver.resolveRegion(headers);
try {
- JsonNode request = readOptionBody(body);
+ JsonNode request = readOptionBody(objectMapper, body);
Boolean enabled = parseReputationMetricsEnabled(request.path("ReputationMetricsEnabled"));
boolean effectiveEnabled = enabled != null && enabled;
sesService.setConfigurationSetReputationOptions(name, effectiveEnabled, region);
@@ -1493,7 +1473,7 @@ public class SesController {
String body) {
String region = regionResolver.resolveRegion(headers);
try {
- JsonNode request = readOptionBody(body);
+ JsonNode request = readOptionBody(objectMapper, body);
sesService.setConfigurationSetTrackingOptions(name, parseTrackingOptions(request), region);
LOG.infov("SES V2 PutConfigurationSetTrackingOptions on {0}", name);
return Response.ok(objectMapper.createObjectNode()).build();
@@ -1509,7 +1489,7 @@ public class SesController {
String body) {
String region = regionResolver.resolveRegion(headers);
try {
- JsonNode request = readOptionBody(body);
+ JsonNode request = readOptionBody(objectMapper, body);
sesService.setConfigurationSetDeliveryOptions(name, parseDeliveryOptions(request), region);
LOG.infov("SES V2 PutConfigurationSetDeliveryOptions on {0}", name);
return Response.ok(objectMapper.createObjectNode()).build();
@@ -1525,7 +1505,7 @@ public class SesController {
String body) {
String region = regionResolver.resolveRegion(headers);
try {
- JsonNode request = readOptionBody(body);
+ JsonNode request = readOptionBody(objectMapper, body);
sesService.setConfigurationSetArchivingOptions(name, parseArchivingOptions(request), region);
LOG.infov("SES V2 PutConfigurationSetArchivingOptions on {0}", name);
return Response.ok(objectMapper.createObjectNode()).build();
@@ -1541,7 +1521,7 @@ public class SesController {
String body) {
String region = regionResolver.resolveRegion(headers);
try {
- JsonNode request = readOptionBody(body);
+ JsonNode request = readOptionBody(objectMapper, body);
JsonNode vdmNode = request.path("VdmOptions");
VdmOptions options = (vdmNode.isMissingNode() || vdmNode.isNull())
? null : parseVdmOptions(vdmNode);
@@ -1560,19 +1540,6 @@ public class SesController {
}
}
- /** Parse a configuration-set option PUT body into a JSON object, treating an empty body as {}. */
- private JsonNode readOptionBody(String body) {
- try {
- JsonNode request = (body == null || body.isBlank())
- ? objectMapper.createObjectNode()
- : objectMapper.readTree(body);
- requireJsonObject(request);
- return request;
- } catch (com.fasterxml.jackson.core.JsonProcessingException e) {
- throw new AwsException("BadRequestException", e.getMessage(), 400);
- }
- }
-
private static Boolean parseReputationMetricsEnabled(JsonNode node) {
if (node.isMissingNode() || node.isNull()) {
return null;
@@ -1584,17 +1551,6 @@ public class SesController {
return node.booleanValue();
}
- /** Read an optional string member, rejecting a non-string value the way the AWS deserialization layer does. */
- private static String parseOptionString(JsonNode node, String field) {
- if (node.isMissingNode() || node.isNull()) {
- return null;
- }
- if (!node.isTextual()) {
- throw new AwsException("BadRequestException", field + " must be a JSON string.", 400);
- }
- return node.asText();
- }
-
private static TrackingOptions parseTrackingOptions(JsonNode node) {
requireOptionObject(node);
TrackingOptions t = new TrackingOptions();
@@ -1895,7 +1851,7 @@ public class SesController {
String body) {
String region = regionResolver.resolveRegion(headers);
try {
- JsonNode request = readOptionBody(body);
+ JsonNode request = readOptionBody(objectMapper, body);
String scalingMode = parseOptionString(request.path("ScalingMode"), "ScalingMode");
sesService.putDedicatedIpPoolScalingAttributes(poolName, scalingMode, region);
LOG.infov("SES V2 PutDedicatedIpPoolScalingAttributes on {0}", poolName);
@@ -2211,7 +2167,7 @@ public class SesController {
@PathParam("ip") String ip, String body) {
String region = regionResolver.resolveRegion(headers);
try {
- JsonNode request = readOptionBody(body);
+ JsonNode request = readOptionBody(objectMapper, body);
String destinationPoolName = parseOptionString(
request.path("DestinationPoolName"), "DestinationPoolName");
sesService.putDedicatedIpInPool(ip, destinationPoolName, region);
@@ -2228,7 +2184,7 @@ public class SesController {
@PathParam("ip") String ip, String body) {
String region = regionResolver.resolveRegion(headers);
try {
- JsonNode request = readOptionBody(body);
+ JsonNode request = readOptionBody(objectMapper, body);
sesService.putDedicatedIpWarmupAttributes(ip,
parseWarmupPercentage(request.path("WarmupPercentage")), region);
LOG.infov("SES V2 PutDedicatedIpWarmupAttributes: {0}", ip);
@@ -2365,10 +2321,10 @@ public class SesController {
// Parse every member first (rejecting wrong JSON types as a serialization error, the way
// AWS does before validation), then validate the parsed values together so all constraint
// violations are aggregated into one response.
- String mailType = requireStringOrAbsent(request, "MailType");
- String websiteUrl = requireStringOrAbsent(request, "WebsiteURL");
- String contactLanguage = requireStringOrAbsent(request, "ContactLanguage");
- String useCaseDescription = requireStringOrAbsent(request, "UseCaseDescription");
+ String mailType = stringMemberOrAbsent(request, "MailType");
+ String websiteUrl = stringMemberOrAbsent(request, "WebsiteURL");
+ String contactLanguage = stringMemberOrAbsent(request, "ContactLanguage");
+ String useCaseDescription = stringMemberOrAbsent(request, "UseCaseDescription");
List<String> additionalContacts = null;
JsonNode contacts = request.path("AdditionalContactEmailAddresses");
@@ -2407,34 +2363,6 @@ public class SesController {
}
}
- // Read a typed string member: absent/null returns null, but a present value of the wrong JSON type
- // is rejected rather than coerced (asText would turn 123 into "123"), the same as the identity and
- // configuration-set string members elsewhere in this controller.
- private static String requireStringOrAbsent(JsonNode parent, String field) {
- JsonNode n = parent.path(field);
- if (n.isMissingNode() || n.isNull()) {
- return null;
- }
- if (!n.isTextual()) {
- throw new AwsException("SerializationException", null, 400);
- }
- return n.textValue();
- }
-
- // Integer variant of stringMemberOrAbsent: absent/null returns null, non-integral JSON is
- // rejected rather than coerced, and so is an integral value outside the int range (intValue
- // would silently truncate it).
- private static Integer intMemberOrAbsent(JsonNode parent, String field) {
- JsonNode n = parent.path(field);
- if (n.isMissingNode() || n.isNull()) {
- return null;
- }
- if (!n.isIntegralNumber() || !n.canConvertToInt()) {
- throw new AwsException("SerializationException", null, 400);
- }
- return n.intValue();
- }
-
// Parse an AWS FeatureStatus (ENABLED/DISABLED) field. A required member that is absent, or any
// value outside the enum, is a Smithy BadRequestException the way AWS returns it; an absent
// optional member defaults to DISABLED (false).
@@ -2468,7 +2396,7 @@ public class SesController {
public Response putAccountDedicatedIpWarmupAttributes(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
- JsonNode request = readOptionBody(body);
+ JsonNode request = readOptionBody(objectMapper, body);
JsonNode enabledNode = request.path("AutoWarmupEnabled");
// AutoWarmupEnabled has a default of false: the SDK omits it when false, so a missing
// member is treated as false rather than rejected. A present value goes through the
@@ -2560,14 +2488,6 @@ public class SesController {
}
}
- private static String readRequiredStringField(JsonNode request, String fieldName) {
- JsonNode node = request.path(fieldName);
- if (node.isMissingNode() || node.isNull() || !node.isTextual()) {
- throw new AwsException("BadRequestException", fieldName + " is required.", 400);
- }
- return node.asText();
- }
-
@GET
@Path("/suppression/addresses/{emailAddress}")
public Response getSuppressedDestination(@Context HttpHeaders headers,
@@ -2880,61 +2800,6 @@ public class SesController {
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;
- }
-
- /**
- * Parse a JSON {@code Tags} array node into a list of tag records. Returns {@code null}
- * when the node is missing or null so callers can decide whether that is an error
- * (TagResource) or a no-op (CreateConfigurationSet / CreateEmailTemplate). Throws
- * {@code BadRequestException} when the node is present but not an array.
- */
- private List<Tag> parseTagsArray(JsonNode tagsNode) {
- if (tagsNode.isMissingNode() || tagsNode.isNull()) {
- return null;
- }
- if (!tagsNode.isArray()) {
- throw new AwsException("BadRequestException", "Tags must be an array.", 400);
- }
- List<Tag> out = new ArrayList<>();
- for (JsonNode t : tagsNode) {
- // Each element must be a JSON object. A scalar/array/null element is a wire deserialization
- // error (AWS returns SerializationException for a scalar/array element; it returns a 500
- // InternalFailure for a null element, a server-side bug we normalize to the same 400).
- if (!t.isObject()) {
- throw new AwsException("SerializationException", null, 400);
- }
- JsonNode key = t.path("Key");
- JsonNode value = t.path("Value");
- // A present-but-non-string Key/Value (number, boolean, object, array) is a wire
- // deserialization error, not a coercible value: AWS restJson1 rejects it with
- // SerializationException rather than turning 123 into "123". A missing/null member is left
- // to the downstream service validation, matching AWS.
- if (nonStringMember(key) || nonStringMember(value)) {
- throw new AwsException("SerializationException", null, 400);
- }
- out.add(new Tag(key.asText(null), value.asText(null)));
- }
- return out;
- }
-
- private static boolean nonStringMember(JsonNode node) {
- return !node.isMissingNode() && !node.isNull() && !node.isTextual();
- }
-
/**
* Parses a {@code SuppressedReasons} JSON array into a list, validating
* structure only; reason values are validated by the service layer.
@@ -2984,34 +2849,6 @@ public class SesController {
return coerceBoolean(enabledNode);
}
- // AWS-verified Jackson coercion for a SES v2 boolean field: a JSON string coerces to true,
- // while a number/null/array/object is a SerializationException.
- private static boolean coerceBoolean(JsonNode node) {
- if (node.isBoolean()) {
- return node.booleanValue();
- }
- if (node.isTextual()) {
- return true;
- }
- if (node.isNull()) {
- throw new AwsException("SerializationException", null, 400);
- }
- if (node.isNumber()) {
- throw new AwsException("SerializationException",
- "NUMBER_VALUE can not be converted to a Boolean", 400);
- }
- throw unexpectedStartError(node);
- }
-
- private static AwsException unexpectedStartError(JsonNode node) {
- if (node.isArray()) {
- return new AwsException("SerializationException",
- "Start of list found where not expected", 400);
- }
- return new AwsException("SerializationException",
- "Start of structure or map found where not expected.", 400);
- }
-
/**
* Parse a V2 SES {@code Content.Simple.Headers} / {@code Content.Template.Headers} array
* (additional message headers, elements use {@code Name}/{@code Value}). Returns an empty
@@ -3059,16 +2896,6 @@ public class SesController {
+ "' failed to satisfy constraint: Member must not be null", 400);
}
- /**
- * Parse a V2 SES {@code EmailTags} / {@code DefaultEmailTags} / {@code ReplacementTags}
- * array (per-message {@link MessageTag} list whose elements use {@code Name}/{@code Value},
- * distinct from the resource-tag {@link Tag} {@code Key}/{@code Value} shape). Note that
- * the per-entry name is {@code ReplacementTags} on the wire — only the top-level field
- * carries the {@code EmailTags} suffix. Returns an empty list when the node is absent so
- * callers can pass it through unconditionally.
- * The {@code fieldName} parameter is reported in the error message when the node is
- * present but not an array.
- */
private static ListManagementOptions parseListManagementOptions(JsonNode node) {
if (node == null || node.isMissingNode() || node.isNull()) {
return null;
@@ -3093,6 +2920,16 @@ public class SesController {
return new ListManagementOptions(listNode.textValue(), topicName);
}
+ /**
+ * Parse a V2 SES {@code EmailTags} / {@code DefaultEmailTags} / {@code ReplacementTags}
+ * array (per-message {@link MessageTag} list whose elements use {@code Name}/{@code Value},
+ * distinct from the resource-tag {@link Tag} {@code Key}/{@code Value} shape). Note that
+ * the per-entry name is {@code ReplacementTags} on the wire: only the top-level field
+ * carries the {@code EmailTags} suffix. Returns an empty list when the node is absent so
+ * callers can pass it through unconditionally.
+ * The {@code fieldName} parameter is reported in the error message when the node is
+ * present but not an array.
+ */
private List<MessageTag> parseEmailTagsArray(JsonNode tagsNode, String fieldName) {
if (tagsNode.isMissingNode() || tagsNode.isNull()) {
return List.of();
@@ -3117,20 +2954,4 @@ public class SesController {
return out;
}
- private static AwsException remapV1Exception(AwsException e) {
- return switch (e.getErrorCode()) {
- case "InvalidParameterValue", "InvalidTemplate", "ValidationError",
- "InvalidRenderingParameter", "MissingRenderingAttribute" ->
- new AwsException("BadRequestException", e.getMessage(), 400);
- case "TemplateDoesNotExist", "ConfigurationSetDoesNotExist",
- "CustomVerificationEmailTemplateDoesNotExist", "FromEmailAddressNotVerified" ->
- new AwsException("NotFoundException", e.getMessage(), 404);
- case "AlreadyExists", "ConfigurationSetAlreadyExists",
- "CustomVerificationEmailTemplateAlreadyExists" ->
- new AwsException("AlreadyExistsException", e.getMessage(), 400);
- case "ConfigurationSetSendingPausedException" ->
- new AwsException("SendingPausedException", e.getMessage(), 400);
- default -> e;
- };
- }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesCvetService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesCvetService.java
index be600b591a..6b91bdf74d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesCvetService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesCvetService.java
@@ -165,7 +165,7 @@ public class SesCvetService {
private static AwsException cvetNotFound(String templateName) {
// v1-native code (verified: CustomVerificationEmailTemplateDoesNotExist / 400).
- // SesController.remapV1Exception translates it to NotFoundException / 404 for the v2 boundary.
+ // SesV2Json.remapV1Exception translates it to NotFoundException / 404 for the v2 boundary.
return new AwsException("CustomVerificationEmailTemplateDoesNotExist",
"Custom verification email template <" + templateName + "> does not exist", 400);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesV2Json.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesV2Json.java
new file mode 100644
index 0000000000..eb2e538c21
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesV2Json.java
@@ -0,0 +1,203 @@
+package io.github.hectorvent.floci.services.ses;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.ses.model.Tag;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Request-parsing helpers shared by the SES v2 REST JSON controllers: body and member shape checks
+ * that answer with the probe-confirmed {@code BadRequestException} / {@code SerializationException}
+ * wordings, the resource {@code Tags} array, and the v1-to-v2 error remapping applied at the v2
+ * boundary. Stateless by design so every controller can call them without a bean; the one helper
+ * that reads a body takes the caller's {@link ObjectMapper}.
+ */
+final class SesV2Json {
+
+ private SesV2Json() {
+ }
+
+ static AwsException remapV1Exception(AwsException e) {
+ return switch (e.getErrorCode()) {
+ case "InvalidParameterValue", "InvalidTemplate", "ValidationError",
+ "InvalidRenderingParameter", "MissingRenderingAttribute" ->
+ new AwsException("BadRequestException", e.getMessage(), 400);
+ case "TemplateDoesNotExist", "ConfigurationSetDoesNotExist",
+ "CustomVerificationEmailTemplateDoesNotExist", "FromEmailAddressNotVerified" ->
+ new AwsException("NotFoundException", e.getMessage(), 404);
+ case "AlreadyExists", "ConfigurationSetAlreadyExists",
+ "CustomVerificationEmailTemplateAlreadyExists" ->
+ new AwsException("AlreadyExistsException", e.getMessage(), 400);
+ case "ConfigurationSetSendingPausedException" ->
+ new AwsException("SendingPausedException", e.getMessage(), 400);
+ default -> e;
+ };
+ }
+
+ static void requireJsonObject(JsonNode root) {
+ if (root == null || !root.isObject()) {
+ throw new AwsException("BadRequestException",
+ "Request body must be a JSON object.", 400);
+ }
+ }
+
+ 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;
+ }
+
+ /**
+ * Parse a JSON {@code Tags} array node into a list of tag records. Returns {@code null}
+ * when the node is missing or null so callers can decide whether that is an error
+ * (TagResource) or a no-op (CreateConfigurationSet / CreateEmailTemplate). Throws
+ * {@code BadRequestException} when the node is present but not an array.
+ */
+ static List<Tag> parseTagsArray(JsonNode tagsNode) {
+ if (tagsNode.isMissingNode() || tagsNode.isNull()) {
+ return null;
+ }
+ if (!tagsNode.isArray()) {
+ throw new AwsException("BadRequestException", "Tags must be an array.", 400);
+ }
+ List<Tag> out = new ArrayList<>();
+ for (JsonNode t : tagsNode) {
+ // Each element must be a JSON object. A scalar/array/null element is a wire deserialization
+ // error (AWS returns SerializationException for a scalar/array element; it returns a 500
+ // InternalFailure for a null element, a server-side bug we normalize to the same 400).
+ if (!t.isObject()) {
+ throw new AwsException("SerializationException", null, 400);
+ }
+ JsonNode key = t.path("Key");
+ JsonNode value = t.path("Value");
+ // A present-but-non-string Key/Value (number, boolean, object, array) is a wire
+ // deserialization error, not a coercible value: AWS restJson1 rejects it with
+ // SerializationException rather than turning 123 into "123". A missing/null member is left
+ // to the downstream service validation, matching AWS.
+ if (nonStringMember(key) || nonStringMember(value)) {
+ throw new AwsException("SerializationException", null, 400);
+ }
+ out.add(new Tag(key.asText(null), value.asText(null)));
+ }
+ return out;
+ }
+
+ private static boolean nonStringMember(JsonNode node) {
+ return !node.isMissingNode() && !node.isNull() && !node.isTextual();
+ }
+
+ /** Parse an option PUT body into a JSON object, treating an empty body as {}. */
+ static JsonNode readOptionBody(ObjectMapper objectMapper, String body) {
+ try {
+ JsonNode request = (body == null || body.isBlank())
+ ? objectMapper.createObjectNode()
+ : objectMapper.readTree(body);
+ requireJsonObject(request);
+ return request;
+ } catch (JsonProcessingException e) {
+ throw new AwsException("BadRequestException", e.getMessage(), 400);
+ }
+ }
+
+ /** Read an optional string member, rejecting a non-string value the way the AWS deserialization layer does. */
+ static String parseOptionString(JsonNode node, String field) {
+ if (node.isMissingNode() || node.isNull()) {
+ return null;
+ }
+ if (!node.isTextual()) {
+ throw new AwsException("BadRequestException", field + " must be a JSON string.", 400);
+ }
+ return node.asText();
+ }
+
+ // AWS-verified Jackson coercion for a SES v2 boolean field: a JSON string coerces to true,
+ // while a number/null/array/object is a SerializationException.
+ static boolean coerceBoolean(JsonNode node) {
+ if (node.isBoolean()) {
+ return node.booleanValue();
+ }
+ if (node.isTextual()) {
+ return true;
+ }
+ if (node.isNull()) {
+ throw new AwsException("SerializationException", null, 400);
+ }
+ if (node.isNumber()) {
+ throw new AwsException("SerializationException",
+ "NUMBER_VALUE can not be converted to a Boolean", 400);
+ }
+ throw unexpectedStartError(node);
+ }
+
+ static AwsException unexpectedStartError(JsonNode node) {
+ if (node.isArray()) {
+ return new AwsException("SerializationException",
+ "Start of list found where not expected", 400);
+ }
+ return new AwsException("SerializationException",
+ "Start of structure or map found where not expected.", 400);
+ }
+
+ // Read a typed string member: absent/null returns null, but a present value of the wrong JSON type
+ // is rejected rather than coerced (asText would turn 123 into "123"), matching AWS.
+ static String stringMemberOrAbsent(JsonNode parent, String field) {
+ JsonNode n = parent.path(field);
+ if (n.isMissingNode() || n.isNull()) {
+ return null;
+ }
+ if (!n.isTextual()) {
+ throw new AwsException("SerializationException", null, 400);
+ }
+ return n.textValue();
+ }
+
+ // Parse an optional array of strings: absent/null returns null, an empty array stays an empty
+ // list (the distinction matters for the suppression-attributes pair rules), and a non-string
+ // element is rejected rather than coerced.
+ static List<String> stringArrayOrAbsent(JsonNode parent, String field) {
+ JsonNode n = parent.path(field);
+ if (n.isMissingNode() || n.isNull()) {
+ return null;
+ }
+ if (!n.isArray()) {
+ throw new AwsException("SerializationException", null, 400);
+ }
+ List<String> values = new ArrayList<>();
+ for (JsonNode item : n) {
+ if (!item.isTextual()) {
+ throw new AwsException("SerializationException", null, 400);
+ }
+ values.add(item.textValue());
+ }
+ return values;
+ }
+
+ // Integer variant of stringMemberOrAbsent: absent/null returns null, non-integral JSON is
+ // rejected rather than coerced, and so is an integral value outside the int range (intValue
+ // would silently truncate it).
+ static Integer intMemberOrAbsent(JsonNode parent, String field) {
+ JsonNode n = parent.path(field);
+ if (n.isMissingNode() || n.isNull()) {
+ return null;
+ }
+ if (!n.isIntegralNumber() || !n.canConvertToInt()) {
+ throw new AwsException("SerializationException", null, 400);
+ }
+ return n.intValue();
+ }
+
+ static String readRequiredStringField(JsonNode request, String fieldName) {
+ JsonNode node = request.path(fieldName);
+ if (node.isMissingNode() || node.isNull() || !node.isTextual()) {
+ throw new AwsException("BadRequestException", fieldName + " is required.", 400);
+ }
+ return node.asText();
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesV2ControllerRegistrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2ControllerRegistrationTest.java
new file mode 100644
index 0000000000..2350934e5b
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2ControllerRegistrationTest.java
@@ -0,0 +1,93 @@
+package io.github.hectorvent.floci.services.ses;
+
+import io.github.hectorvent.floci.core.common.ResolvedServiceCatalog;
+import io.github.hectorvent.floci.core.common.ServiceDescriptor;
+import io.quarkus.test.junit.QuarkusTest;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.Test;
+
+import java.io.File;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Tripwire for the SES v2 controller split: every JAX-RS resource class in this package that
+ * serves {@code /v2/email} must be listed in the SES descriptor's resource classes in
+ * {@code ResolvedServiceCatalog}. {@code ServiceEnabledFilter} and
+ * {@code AwsRestJsonErrorHeaderFilter} resolve the service by resource class first and only fall
+ * back to the SigV4 credential scope, so a controller missing from the catalog still works for
+ * signed SDK calls and silently loses the service-disabled gate and the {@code x-amzn-errortype}
+ * header for unsigned ones. The internal {@code /_aws/ses} controllers are outside the AWS surface
+ * and stay unregistered on purpose.
+ */
+@QuarkusTest
+class SesV2ControllerRegistrationTest {
+
+ private static final String V2_PREFIX = "/v2/email";
+
+ @Inject
+ ResolvedServiceCatalog catalog;
+
+ @Test
+ void everyV2EmailResourceClassIsRegisteredOnTheSesDescriptor() throws Exception {
+ List<Class<?>> v2Controllers = v2EmailResourceClasses();
+ assertTrue(v2Controllers.contains(SesController.class),
+ "scan must at least find SesController; found " + v2Controllers);
+
+ List<String> unregistered = new ArrayList<>();
+ for (Class<?> controller : v2Controllers) {
+ String owner = catalog.byResourceClass(controller)
+ .map(ServiceDescriptor::externalKey).orElse(null);
+ if (!"email".equals(owner)) {
+ unregistered.add(controller.getSimpleName() + " (resolved to " + owner + ")");
+ }
+ }
+ assertEquals(List.of(), unregistered,
+ "add these to the SES descriptor's resource classes in ResolvedServiceCatalog");
+ }
+
+ @Test
+ void scanLeavesTheInternalControllersOutOfTheRule() throws Exception {
+ // /_aws/ses is Floci's own inspection surface, not an AWS route, and is unregistered on
+ // purpose; the prefix filter must not pull it into the registration requirement.
+ List<Class<?>> v2Controllers = v2EmailResourceClasses();
+ assertFalse(v2Controllers.contains(SesInspectionController.class));
+ assertFalse(v2Controllers.contains(SesUnsubscribeController.class));
+ assertTrue(catalog.byResourceClass(SesInspectionController.class).isEmpty());
+ assertTrue(catalog.byResourceClass(SesUnsubscribeController.class).isEmpty());
+ }
+
+ private List<Class<?>> v2EmailResourceClasses() throws Exception {
+ URI codeSource = SesController.class.getProtectionDomain().getCodeSource()
+ .getLocation().toURI();
+ Path classesDir = Path.of(codeSource);
+ String packagePrefix = SesController.class.getPackageName() + ".";
+ List<Class<?>> found = new ArrayList<>();
+ try (Stream<Path> paths = Files.walk(classesDir)) {
+ List<Path> classFiles = paths.filter(p -> p.toString().endsWith(".class")).toList();
+ for (Path p : classFiles) {
+ String name = classesDir.relativize(p).toString()
+ .replace(File.separatorChar, '.')
+ .replaceAll("\\.class$", "");
+ if (!name.startsWith(packagePrefix) || name.contains("$")) {
+ continue;
+ }
+ Class<?> type = Class.forName(name, false, getClass().getClassLoader());
+ // jakarta.ws.rs.Path clashes with the java.nio.file.Path this scan is built on.
+ jakarta.ws.rs.Path route = type.getAnnotation(jakarta.ws.rs.Path.class);
+ if (route != null && route.value().startsWith(V2_PREFIX)) {
+ found.add(type);
+ }
+ }
+ }
+ return found;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesV2JsonTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2JsonTest.java
new file mode 100644
index 0000000000..569e9e549f
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2JsonTest.java
@@ -0,0 +1,200 @@
+package io.github.hectorvent.floci.services.ses;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.ses.model.Tag;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.function.Executable;
+
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for the request-parsing helpers shared by the SES v2 controllers. Each helper's
+ * accept / reject split and its wording were previously pinned only through the controller
+ * integration tests; these pin them directly so the controllers can move without re-proving them.
+ */
+class SesV2JsonTest {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private static JsonNode json(String text) {
+ try {
+ return MAPPER.readTree(text);
+ } catch (Exception e) {
+ throw new AssertionError(e);
+ }
+ }
+
+ private static AwsException assertAws(String code, int status, Executable call) {
+ AwsException e = assertThrows(AwsException.class, call);
+ assertEquals(code, e.getErrorCode());
+ assertEquals(status, e.getHttpStatus());
+ return e;
+ }
+
+ @Test
+ void remapV1Exception_mapsEachV1FamilyAndPassesOthersThrough() {
+ AwsException bad = SesV2Json.remapV1Exception(
+ new AwsException("InvalidParameterValue", "m", 400));
+ assertEquals("BadRequestException", bad.getErrorCode());
+ assertEquals("m", bad.getMessage());
+ assertEquals(400, bad.getHttpStatus());
+ assertEquals("BadRequestException", SesV2Json.remapV1Exception(
+ new AwsException("MissingRenderingAttribute", "m", 400)).getErrorCode());
+
+ AwsException notFound = SesV2Json.remapV1Exception(
+ new AwsException("ConfigurationSetDoesNotExist", "m", 400));
+ assertEquals("NotFoundException", notFound.getErrorCode());
+ assertEquals(404, notFound.getHttpStatus());
+
+ assertEquals("AlreadyExistsException", SesV2Json.remapV1Exception(new AwsException(
+ "CustomVerificationEmailTemplateAlreadyExists", "m", 400)).getErrorCode());
+ assertEquals("SendingPausedException", SesV2Json.remapV1Exception(new AwsException(
+ "ConfigurationSetSendingPausedException", "m", 400)).getErrorCode());
+
+ AwsException untouched = new AwsException("NotFoundException", "already v2", 404);
+ assertSame(untouched, SesV2Json.remapV1Exception(untouched));
+ }
+
+ @Test
+ void requireJsonObject_rejectsNullAndNonObjects() {
+ assertEquals("Request body must be a JSON object.", assertAws("BadRequestException", 400,
+ () -> SesV2Json.requireJsonObject(null)).getMessage());
+ assertAws("BadRequestException", 400, () -> SesV2Json.requireJsonObject(json("[]")));
+ SesV2Json.requireJsonObject(json("{}"));
+ }
+
+ @Test
+ void requireObjectOrAbsent_returnsChild_rejectsScalars() {
+ assertTrue(SesV2Json.requireObjectOrAbsent(json("{}"), "Options").isMissingNode());
+ assertTrue(SesV2Json.requireObjectOrAbsent(json("{\"Options\":null}"), "Options").isNull());
+ JsonNode nested = json("{\"Options\":{\"a\":\"x\"}}");
+ assertEquals("x", SesV2Json.requireObjectOrAbsent(nested, "Options").path("a").asText());
+ assertEquals("Options must be a JSON object.",
+ assertAws("BadRequestException", 400, () -> SesV2Json.requireObjectOrAbsent(
+ json("{\"Options\":1}"), "Options")).getMessage());
+ }
+
+ @Test
+ void parseTagsArray_absentIsNull_shapeErrorsAreWireErrors() {
+ assertNull(SesV2Json.parseTagsArray(json("{}").path("Tags")));
+ assertNull(SesV2Json.parseTagsArray(json("{\"Tags\":null}").path("Tags")));
+ assertEquals("Tags must be an array.", assertAws("BadRequestException", 400,
+ () -> SesV2Json.parseTagsArray(json("{\"Tags\":{}}").path("Tags"))).getMessage());
+ assertAws("SerializationException", 400,
+ () -> SesV2Json.parseTagsArray(json("[\"k=v\"]")));
+ assertAws("SerializationException", 400,
+ () -> SesV2Json.parseTagsArray(json("[{\"Key\":1,\"Value\":\"v\"}]")));
+ assertAws("SerializationException", 400,
+ () -> SesV2Json.parseTagsArray(json("[{\"Key\":\"k\",\"Value\":[]}]")));
+
+ List<Tag> tags = SesV2Json.parseTagsArray(
+ json("[{\"Key\":\"k\",\"Value\":\"v\"},{\"Key\":\"only\"}]"));
+ assertEquals(2, tags.size());
+ assertEquals("k", tags.get(0).key());
+ assertEquals("v", tags.get(0).value());
+ // A missing member is left to the downstream tag validation rather than rejected here.
+ assertEquals("only", tags.get(1).key());
+ assertNull(tags.get(1).value());
+ }
+
+ @Test
+ void readOptionBody_blankIsEmptyObject_badShapesAre400() {
+ assertTrue(SesV2Json.readOptionBody(MAPPER, null).isObject());
+ assertTrue(SesV2Json.readOptionBody(MAPPER, " ").isObject());
+ assertEquals("REQUIRE", SesV2Json.readOptionBody(MAPPER, "{\"HttpsPolicy\":\"REQUIRE\"}")
+ .path("HttpsPolicy").asText());
+ assertEquals("Request body must be a JSON object.", assertAws("BadRequestException", 400,
+ () -> SesV2Json.readOptionBody(MAPPER, "[1]")).getMessage());
+ assertAws("BadRequestException", 400, () -> SesV2Json.readOptionBody(MAPPER, "{not json"));
+ }
+
+ @Test
+ void parseOptionString_absentIsNull_nonStringIs400() {
+ JsonNode node = json("{\"TlsPolicy\":\"REQUIRE\",\"Bad\":true}");
+ assertNull(SesV2Json.parseOptionString(node.path("Missing"), "Missing"));
+ assertEquals("REQUIRE", SesV2Json.parseOptionString(node.path("TlsPolicy"), "TlsPolicy"));
+ assertEquals("Bad must be a JSON string.", assertAws("BadRequestException", 400,
+ () -> SesV2Json.parseOptionString(node.path("Bad"), "Bad")).getMessage());
+ }
+
+ @Test
+ void coerceBoolean_matchesAwsJacksonCoercion() {
+ JsonNode node = json(
+ "{\"t\":true,\"f\":false,\"s\":\"no\",\"z\":null,\"n\":0,\"a\":[],\"o\":{}}");
+ assertTrue(SesV2Json.coerceBoolean(node.path("t")));
+ assertFalse(SesV2Json.coerceBoolean(node.path("f")));
+ // A JSON string coerces to true regardless of its text (probe-confirmed).
+ assertTrue(SesV2Json.coerceBoolean(node.path("s")));
+ assertNull(assertAws("SerializationException", 400,
+ () -> SesV2Json.coerceBoolean(node.path("z"))).getMessage());
+ assertEquals("NUMBER_VALUE can not be converted to a Boolean",
+ assertAws("SerializationException", 400,
+ () -> SesV2Json.coerceBoolean(node.path("n"))).getMessage());
+ assertEquals("Start of list found where not expected",
+ assertAws("SerializationException", 400,
+ () -> SesV2Json.coerceBoolean(node.path("a"))).getMessage());
+ assertEquals("Start of structure or map found where not expected.",
+ assertAws("SerializationException", 400,
+ () -> SesV2Json.coerceBoolean(node.path("o"))).getMessage());
+ }
+
+ @Test
+ void unexpectedStartError_distinguishesListFromStructure() {
+ assertEquals("Start of list found where not expected",
+ SesV2Json.unexpectedStartError(json("[]")).getMessage());
+ assertEquals("Start of structure or map found where not expected.",
+ SesV2Json.unexpectedStartError(json("{}")).getMessage());
+ assertEquals("Start of structure or map found where not expected.",
+ SesV2Json.unexpectedStartError(json("1")).getMessage());
+ }
+
+ @Test
+ void stringMemberOrAbsent_absentAndNullAreNull_wrongTypeIsWireError() {
+ JsonNode node = json("{\"s\":\"x\",\"z\":null,\"n\":1}");
+ assertEquals("x", SesV2Json.stringMemberOrAbsent(node, "s"));
+ assertNull(SesV2Json.stringMemberOrAbsent(node, "z"));
+ assertNull(SesV2Json.stringMemberOrAbsent(node, "missing"));
+ assertAws("SerializationException", 400, () -> SesV2Json.stringMemberOrAbsent(node, "n"));
+ }
+
+ @Test
+ void stringArrayOrAbsent_keepsEmptyListDistinctFromAbsent() {
+ JsonNode node = json("{\"a\":[\"x\",\"y\"],\"e\":[],\"z\":null,\"s\":\"x\",\"m\":[1]}");
+ assertEquals(List.of("x", "y"), SesV2Json.stringArrayOrAbsent(node, "a"));
+ assertEquals(List.of(), SesV2Json.stringArrayOrAbsent(node, "e"));
+ assertNull(SesV2Json.stringArrayOrAbsent(node, "z"));
+ assertNull(SesV2Json.stringArrayOrAbsent(node, "missing"));
+ assertAws("SerializationException", 400, () -> SesV2Json.stringArrayOrAbsent(node, "s"));
+ assertAws("SerializationException", 400, () -> SesV2Json.stringArrayOrAbsent(node, "m"));
+ }
+
+ @Test
+ void intMemberOrAbsent_rejectsNonIntegralAndOutOfRange() {
+ JsonNode node = json("{\"i\":5,\"f\":1.5,\"big\":1099511627776,\"s\":\"5\",\"z\":null}");
+ assertEquals(5, SesV2Json.intMemberOrAbsent(node, "i"));
+ assertNull(SesV2Json.intMemberOrAbsent(node, "z"));
+ assertNull(SesV2Json.intMemberOrAbsent(node, "missing"));
+ assertAws("SerializationException", 400, () -> SesV2Json.intMemberOrAbsent(node, "f"));
+ assertAws("SerializationException", 400, () -> SesV2Json.intMemberOrAbsent(node, "big"));
+ assertAws("SerializationException", 400, () -> SesV2Json.intMemberOrAbsent(node, "s"));
+ }
+
+ @Test
+ void readRequiredStringField_missingNullOrNonStringIsRequiredError() {
+ JsonNode node = json("{\"PoolName\":\"p\",\"Bad\":1,\"Nil\":null}");
+ assertEquals("p", SesV2Json.readRequiredStringField(node, "PoolName"));
+ for (String field : List.of("Missing", "Bad", "Nil")) {
+ assertEquals(field + " is required.", assertAws("BadRequestException", 400,
+ () -> SesV2Json.readRequiredStringField(node, field)).getMessage());
+ }
+ }
+}