Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(ses): check v2 metrics, import, export and account bodies against the service model (#5900)

Kenshin Okinakaf9bd725b518e
diff --git a/docs/services/ses.md b/docs/services/ses.md
index cec39b21e1..856cedab2f 100644
--- a/docs/services/ses.md
+++ b/docs/services/ses.md
@@ -505,7 +505,7 @@ S/MIME certificate associations are stored per region and never used: Floci does
### Request member types
-The operations whose body nests a structure in a structure, or holds a list of structures, check the request body against the SES v2 service model before anything else is validated, as AWS's restJson1 deserializer does: the send operations (`SendEmail`, `SendBulkEmail`, `SendCustomVerificationEmail`), `CreateConfigurationSet`, `UpdateConfigurationSet`, `PutConfigurationSetSuppressionOptions`, `PutConfigurationSetVdmOptions`, `CreateConfigurationSetEventDestination`, `UpdateConfigurationSetEventDestination`, `CreateContactList`, `UpdateContactList`, `CreateContact`, `UpdateContact` and `ListContacts`. In those operations, the first body member of the wrong JSON type, in body order, is a `SerializationException` with AWS's deserializer message:
+The operations whose body nests a structure in a structure, or holds a list of structures, check the request body against the SES v2 service model before anything else is validated, as AWS's restJson1 deserializer does: the send operations (`SendEmail`, `SendBulkEmail`, `SendCustomVerificationEmail`), `CreateConfigurationSet`, `UpdateConfigurationSet`, `PutConfigurationSetSuppressionOptions`, `PutConfigurationSetVdmOptions`, `CreateConfigurationSetEventDestination`, `UpdateConfigurationSetEventDestination`, `CreateContactList`, `UpdateContactList`, `CreateContact`, `UpdateContact`, `ListContacts`, `PutAccountSuppressionAttributes`, `PutAccountVdmAttributes`, `BatchGetMetricData`, `CreateImportJob` and `CreateExportJob`. In those operations, the first body member of the wrong JSON type, in body order, is a `SerializationException` with AWS's deserializer message:
| Member type | Value sent | Message |
|---|---|---|
@@ -514,7 +514,7 @@ The operations whose body nests a structure in a structure, or holds a list of s
| structure, map | array / any other non-object | `Start of list found where not expected` / `Expected null` |
| list | object / any other non-array | `Start of structure or map found where not expected.` / `Expected list or null` |
-A JSON `null` member counts as absent. A `null` address list element passes this check and fails later, as on AWS: `SendEmail` answers `Invalid email address null.` after its content and sender checks and before the tenant lookup, and `SendBulkEmail` reports it as the `INVALID_PARAMETER` status of the entry it belongs to (of every entry for a `null` Reply-To), or as `Destination cannot be empty` when no entry of the request has a non-null recipient. A `null` element of `Topics` (`CreateContactList`, `UpdateContactList`) or `TopicPreferences` (`CreateContact`, `UpdateContact`) also passes this check, but there AWS answers it with a `500 InternalFailure`, which Floci replaces with `BadRequestException` naming the element ("1 validation error detected: Value at 'topics.1.member.topicName' failed to satisfy constraint: Member must not be null"). The account-level sending switch is still checked first, so a paused account answers `SendingPausedException` even for a malformed body.
+A JSON `null` member counts as absent. A `null` address list element passes this check and fails later, as on AWS: `SendEmail` answers `Invalid email address null.` after its content and sender checks and before the tenant lookup, and `SendBulkEmail` reports it as the `INVALID_PARAMETER` status of the entry it belongs to (of every entry for a `null` Reply-To), or as `Destination cannot be empty` when no entry of the request has a non-null recipient. A `null` element of `Topics` (`CreateContactList`, `UpdateContactList`) or `TopicPreferences` (`CreateContact`, `UpdateContact`) also passes this check, but there AWS answers it with a `500 InternalFailure`, which Floci replaces with `BadRequestException` naming the element ("1 validation error detected: Value at 'topics.1.member.topicName' failed to satisfy constraint: Member must not be null"). The account-level sending switch is still checked first, so a paused account answers `SendingPausedException` even for a malformed body. Likewise `BatchGetMetricData` checks that Virtual Deliverability Manager is enabled before it reads the body.
The other operations check their members one at a time, and some of them still answer a wrong JSON type with `BadRequestException`.
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesAccountController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesAccountController.java
index 23ffeff245..4c59c1d4a4 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesAccountController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesAccountController.java
@@ -30,7 +30,6 @@ import static io.github.hectorvent.floci.services.ses.SesV2Json.coerceBooleanOrF
import static io.github.hectorvent.floci.services.ses.SesV2Json.readOptionBody;
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.stringMemberOrAbsent;
/**
@@ -135,21 +134,19 @@ public class SesAccountController {
public Response putAccountVdmAttributes(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
- JsonNode request = (body == null || body.isBlank())
- ? objectMapper.createObjectNode()
- : objectMapper.readTree(body);
- requireJsonObject(request);
+ JsonNode request = readOptionBody(objectMapper, body);
+ SesV2RequestShapes.check("PutAccountVdmAttributes", request);
JsonNode vdm = request.path("VdmAttributes");
- if (!vdm.isObject()) {
+ if (vdm.isMissingNode() || vdm.isNull()) {
throw new AwsException("BadRequestException", "VdmAttributes is required.", 400);
}
boolean vdmEnabled = parseFeatureStatus(vdm, "VdmEnabled",
"vdmAttributes.vdmEnabled", true);
boolean engagement = parseFeatureStatus(
- requireObjectOrAbsent(vdm, "DashboardAttributes"), "EngagementMetrics",
+ vdm.path("DashboardAttributes"), "EngagementMetrics",
"vdmAttributes.dashboardAttributes.engagementMetrics", false);
boolean osd = parseFeatureStatus(
- requireObjectOrAbsent(vdm, "GuardianAttributes"), "OptimizedSharedDelivery",
+ vdm.path("GuardianAttributes"), "OptimizedSharedDelivery",
"vdmAttributes.guardianAttributes.optimizedSharedDelivery", false);
accountService.putAccountVdmAttributes(region,
new AccountVdmAttributes(vdmEnabled, engagement, osd));
@@ -158,8 +155,6 @@ public class SesAccountController {
return Response.ok(objectMapper.createObjectNode()).build();
} catch (AwsException e) {
throw remapV1Exception(e);
- } catch (JsonProcessingException e) {
- throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@@ -240,31 +235,21 @@ public class SesAccountController {
public Response putAccountSuppressionAttributes(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
- JsonNode request = (body == null || body.isBlank())
- ? objectMapper.createObjectNode()
- : objectMapper.readTree(body);
- requireJsonObject(request);
- JsonNode reasonsNode = request.path("SuppressedReasons");
+ JsonNode request = readOptionBody(objectMapper, body);
+ SesV2RequestShapes.check("PutAccountSuppressionAttributes", request);
List<String> reasons = new ArrayList<>();
- if (!reasonsNode.isMissingNode() && !reasonsNode.isNull()) {
- if (!reasonsNode.isArray()) {
- throw new AwsException("BadRequestException", "SuppressedReasons must be an array.", 400);
- }
- for (JsonNode r : reasonsNode) {
- if (r.isNull() || !r.isTextual()) {
- throw new AwsException("BadRequestException",
- "SuppressedReasons entries must be strings.", 400);
- }
- reasons.add(r.asText());
+ for (JsonNode r : request.path("SuppressedReasons")) {
+ if (r.isNull()) {
+ throw new AwsException("BadRequestException",
+ "SuppressedReasons entries must be strings.", 400);
}
+ reasons.add(r.textValue());
}
suppressionService.putAccountSuppressionAttributes(region, reasons);
LOG.infov("SES V2 PutAccountSuppressionAttributes: {0}", reasons);
return Response.ok(objectMapper.createObjectNode()).build();
} catch (AwsException e) {
throw remapV1Exception(e);
- } catch (JsonProcessingException e) {
- throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesExportFilters.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesExportFilters.java
index 7a89fb5340..3c50add5d2 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesExportFilters.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesExportFilters.java
@@ -1,7 +1,6 @@
package io.github.hectorvent.floci.services.ses;
import com.fasterxml.jackson.databind.JsonNode;
-import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import java.util.ArrayList;
@@ -84,9 +83,9 @@ final class SesExportFilters {
}
/**
- * Rejects a filter block that is not an object and a member that is not a list of strings,
- * rather than reading it as no filter at all and quietly returning rows the caller excluded,
- * then holds each member to the length the model gives it.
+ * The SES v2 shape check has already rejected a filter block or member of the wrong JSON type.
+ * This rejects a {@code null} element of a member list, which that check leaves to the
+ * operation, then holds each member to the length the model gives it.
*/
static void validate(JsonNode insights) {
List<String> violations = new ArrayList<>();
@@ -101,9 +100,6 @@ final class SesExportFilters {
if (filters.isMissingNode() || filters.isNull()) {
return;
}
- if (!filters.isObject()) {
- throw new AwsException("SerializationException", null, 400);
- }
for (Member member : Member.values()) {
List<String> values = stringArrayOrAbsent(filters, member.wireName);
if (values != null && member.maxValues != NO_LIMIT && values.size() > member.maxValues) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobController.java
index c4e2d1f4a7..e4d02fe684 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobController.java
@@ -59,6 +59,7 @@ public class SesExportJobController {
public Response createExportJob(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
JsonNode request = readOptionBody(objectMapper, body);
+ SesV2RequestShapes.check("CreateExportJob", request);
JsonNode destination = request.path("ExportDestination");
JsonNode dataSource = request.path("ExportDataSource");
ExportJob job = exportJobService.createExportJob(region, regionResolver.getAccountId(),
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobService.java
index 39eb37682f..6791c12947 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesExportJobService.java
@@ -39,7 +39,6 @@ import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
import static io.github.hectorvent.floci.services.ses.SesV2Json.intMemberOrAbsent;
-import static io.github.hectorvent.floci.services.ses.SesV2Json.stringMemberOrAbsent;
/**
* SES V2 export jobs. A job reads the timelines already stored at send time, renders them through
@@ -126,20 +125,20 @@ public class SesExportJobService implements Resettable {
/**
* The request's already-parsed {@code ExportDataSource} and {@code ExportDestination}. The
- * controller keeps the JSON shape checks; the service owns the order the service-level rules
- * fire in.
+ * controller has checked their JSON types against the SES v2 shapes; the service owns the order
+ * the service-level rules fire in.
*/
public ExportJob createExportJob(String region, String accountId, JsonNode exportDataSource,
JsonNode exportDestination, Runnable vdmGate) {
- JsonNode metrics = objectMemberOrAbsent(exportDataSource, "MetricsDataSource");
- JsonNode insights = objectMemberOrAbsent(exportDataSource, "MessageInsightsDataSource");
+ JsonNode metrics = exportDataSource.path("MetricsDataSource");
+ JsonNode insights = exportDataSource.path("MessageInsightsDataSource");
if (metrics.isObject() == insights.isObject()) {
throw new AwsException("BadRequestException", "One data source must be provided", 400);
}
if (!exportDestination.isObject()) {
throw notNull("exportDestination");
}
- String dataFormat = stringMemberOrAbsent(exportDestination, "DataFormat");
+ String dataFormat = exportDestination.path("DataFormat").textValue();
if (dataFormat == null) {
throw notNull("exportDestination.dataFormat");
}
@@ -545,18 +544,6 @@ public class SesExportJobService implements Resettable {
List.of("Value at '" + member + "' failed to satisfy constraint: Member must not be null"));
}
- /**
- * A union member of the wrong JSON type read as absent, so a request carrying a valid source
- * plus a malformed one passed the exactly-one check and silently exported the valid half.
- */
- private static JsonNode objectMemberOrAbsent(JsonNode parent, String field) {
- JsonNode member = parent.path(field);
- if (!member.isMissingNode() && !member.isNull() && !member.isObject()) {
- throw new AwsException("SerializationException", null, 400);
- }
- return member;
- }
-
/**
* The model bounds {@code MaxResults} at 1 to 10000. An unchecked negative value reached
* {@code subList} inside the filter and surfaced as a 500.
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesExportMetrics.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesExportMetrics.java
index 65f7013390..f47ecc33fa 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesExportMetrics.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesExportMetrics.java
@@ -18,7 +18,6 @@ import java.util.Map;
import java.util.Set;
import static io.github.hectorvent.floci.services.ses.SesV2Json.stringArrayOrAbsent;
-import static io.github.hectorvent.floci.services.ses.SesV2Json.stringMemberOrAbsent;
/**
* The metrics half of an export job. Every count comes from {@link SesMetricData}, the same
@@ -61,7 +60,7 @@ final class SesExportMetrics {
* the per-value rules the batch operation applies.
*/
static void validate(JsonNode metrics) {
- requireWireTypes(metrics);
+ rejectNullElements(metrics);
List<String> violations = new ArrayList<>();
validateDimensions(metrics.path("Dimensions"), violations);
JsonNode namespace = metrics.path("Namespace");
@@ -76,35 +75,22 @@ final class SesExportMetrics {
}
/**
- * The deserialization-level checks, which come first and answer {@code SerializationException}
- * like every other typed SES v2 member: a dimension value list of numbers was otherwise
- * coerced to strings, and a metric that is a bare string was read as one with no members at
- * all, both producing a successful but meaningless export.
+ * The SES v2 shape check has already rejected every member of the wrong JSON type, but it
+ * leaves a {@code null} list element to the operation. AWS's answer for one was not probed;
+ * Floci treats it as a {@code SerializationException}, ahead of the constraints.
*/
- private static void requireWireTypes(JsonNode metrics) {
+ private static void rejectNullElements(JsonNode metrics) {
JsonNode dimensions = metrics.path("Dimensions");
if (present(dimensions)) {
- if (!dimensions.isObject()) {
- throw serializationError();
- }
Iterator<String> names = dimensions.fieldNames();
while (names.hasNext()) {
stringArrayOrAbsent(dimensions, names.next());
}
}
- stringMemberOrAbsent(metrics, "Namespace");
- JsonNode requested = metrics.path("Metrics");
- if (present(requested)) {
- if (!requested.isArray()) {
+ for (JsonNode metric : metrics.path("Metrics")) {
+ if (metric.isNull()) {
throw serializationError();
}
- for (JsonNode metric : requested) {
- if (!metric.isObject()) {
- throw serializationError();
- }
- stringMemberOrAbsent(metric, "Name");
- stringMemberOrAbsent(metric, "Aggregation");
- }
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesImportJobController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesImportJobController.java
index edf1a88773..38541c62b1 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesImportJobController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesImportJobController.java
@@ -29,7 +29,6 @@ import static io.github.hectorvent.floci.services.ses.SesV2Json.putTimestamp;
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.stringMemberOrAbsent;
/**
@@ -70,18 +69,19 @@ public class SesImportJobController {
}
JsonNode request = strictReader.readTree(body);
requireJsonObject(request);
- JsonNode source = requireObjectOrAbsent(request, "ImportDataSource");
- if (!source.isObject()) {
+ SesV2RequestShapes.check("CreateImportJob", request);
+ JsonNode source = request.path("ImportDataSource");
+ if (source.isMissingNode() || source.isNull()) {
throw new AwsException("BadRequestException", "ImportDataSource is required.", 400);
}
String s3Url = readRequiredStringField(source, "S3Url");
String dataFormat = readRequiredStringField(source, "DataFormat");
- JsonNode destination = requireObjectOrAbsent(request, "ImportDestination");
- if (!destination.isObject()) {
+ JsonNode destination = request.path("ImportDestination");
+ if (destination.isMissingNode() || destination.isNull()) {
throw new AwsException("BadRequestException", "ImportDestination is required.", 400);
}
- JsonNode suppression = requireObjectOrAbsent(destination, "SuppressionListDestination");
- JsonNode contactList = requireObjectOrAbsent(destination, "ContactListDestination");
+ JsonNode suppression = destination.path("SuppressionListDestination");
+ JsonNode contactList = destination.path("ContactListDestination");
if (suppression.isObject() == contactList.isObject()) {
throw new AwsException("BadRequestException",
"ImportDestination must contain exactly one of SuppressionListDestination "
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesMetricsController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesMetricsController.java
index ca183ff382..58e3159f12 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesMetricsController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesMetricsController.java
@@ -33,7 +33,6 @@ import java.util.regex.Pattern;
import static io.github.hectorvent.floci.services.ses.SesV2Json.epochSeconds;
import static io.github.hectorvent.floci.services.ses.SesV2Json.readOptionBody;
-import static io.github.hectorvent.floci.services.ses.SesV2Json.stringMemberOrAbsent;
/**
* SES V2 metric data ({@code POST /v2/email/metrics/batch}), the aggregate view of the same stored
@@ -86,6 +85,7 @@ public class SesMetricsController {
accountService.requireVdmEnabled(region);
JsonNode request = readOptionBody(objectMapper, body);
+ SesV2RequestShapes.check("BatchGetMetricData", request);
List<JsonNode> queryNodes = requireQueries(request);
requireUniqueIds(queryNodes);
requireKnownDimensionNames(queryNodes);
@@ -164,11 +164,6 @@ public class SesMetricsController {
private static List<JsonNode> requireQueries(JsonNode request) {
JsonNode queries = request.path("Queries");
- // Absent and null fail the list constraint, but a present value of the wrong shape is a
- // deserialization failure, the same treatment the Dimensions map gets below.
- if (!queries.isMissingNode() && !queries.isNull() && !queries.isArray()) {
- throw SesV2Json.unexpectedStartError(queries);
- }
if (!queries.isArray() || queries.isEmpty()) {
throw listConstraint("Member must have length greater than or equal to 1");
}
@@ -188,7 +183,7 @@ public class SesMetricsController {
private static void requireUniqueIds(List<JsonNode> queries) {
Set<String> seen = new LinkedHashSet<>();
for (JsonNode query : queries) {
- String id = stringMemberOrAbsent(query, "Id");
+ String id = query.path("Id").textValue();
if (id != null && !seen.add(id)) {
throw new AwsException("BadRequestException",
"All queries must have a unique identifier.", 400);
@@ -206,11 +201,6 @@ public class SesMetricsController {
if (dimensions.isMissingNode() || dimensions.isNull()) {
continue;
}
- // A map member has to be a JSON object: an array or a scalar is a deserialization
- // failure, not an absent Dimensions that silently drops the filter.
- if (!dimensions.isObject()) {
- throw SesV2Json.unexpectedStartError(dimensions);
- }
Iterator<String> names = dimensions.fieldNames();
while (names.hasNext()) {
if (!SesMetricData.DIMENSION_NAMES.contains(names.next())) {
@@ -231,17 +221,17 @@ public class SesMetricsController {
for (int i = 0; i < queries.size(); i++) {
JsonNode query = queries.get(i);
int position = i + 1;
- String metric = stringMemberOrAbsent(query, "Metric");
+ String metric = query.path("Metric").textValue();
if (metric == null || !SesMetricData.METRICS.contains(metric)) {
violations.add(memberConstraint(position, "metric",
"Member must satisfy enum value set: " + METRIC_ENUM));
}
- String namespace = stringMemberOrAbsent(query, "Namespace");
+ String namespace = query.path("Namespace").textValue();
if (namespace == null || !"VDM".equals(namespace)) {
violations.add(memberConstraint(position, "namespace",
"Member must satisfy enum value set: " + NAMESPACE_ENUM));
}
- String id = stringMemberOrAbsent(query, "Id");
+ String id = query.path("Id").textValue();
if (id == null || id.isEmpty()) {
violations.add(memberConstraint(position, "id",
"Member must have length greater than or equal to 1"));
@@ -295,8 +285,8 @@ public class SesMetricsController {
"Invalid interval, can request at most 60 days. Please partition your "
+ "requested interval.", 400);
}
- return new SesMetricData.Query(stringMemberOrAbsent(query, "Id"),
- stringMemberOrAbsent(query, "Metric"), dimensions, startDate, endDate);
+ return new SesMetricData.Query(query.path("Id").textValue(),
+ query.path("Metric").textValue(), dimensions, startDate, endDate);
}
/**
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesAccountMemberTypeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesAccountMemberTypeIntegrationTest.java
new file mode 100644
index 0000000000..e15f11174a
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesAccountMemberTypeIntegrationTest.java
@@ -0,0 +1,72 @@
+package io.github.hectorvent.floci.services.ses;
+
+import io.quarkus.test.junit.QuarkusTest;
+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.github.hectorvent.floci.services.ses.SesV2SerializationErrors.EXPECTED_LIST;
+import static io.github.hectorvent.floci.services.ses.SesV2SerializationErrors.EXPECTED_NULL;
+import static io.github.hectorvent.floci.services.ses.SesV2SerializationErrors.LIST;
+import static io.github.hectorvent.floci.services.ses.SesV2SerializationErrors.NUMBER;
+import static io.github.hectorvent.floci.services.ses.SesV2SerializationErrors.STRUCTURE;
+import static io.github.hectorvent.floci.services.ses.SesV2SerializationErrors.assertError;
+import static io.github.hectorvent.floci.services.ses.SesV2SerializationErrors.assertSerializationException;
+
+/**
+ * PutAccountVdmAttributes and PutAccountSuppressionAttributes check their body against the SES v2
+ * shapes, so a member of the wrong JSON type, nested ones included, is a SerializationException
+ * ahead of the required and enum checks. Every case fails before the account state is touched.
+ */
+@QuarkusTest
+class SesAccountMemberTypeIntegrationTest {
+
+ private static final String VDM = "/v2/email/account/vdm";
+ private static final String SUPPRESSION = "/v2/email/account/suppression";
+
+ static Stream<Arguments> putAccountVdmAttributesCases() {
+ return Stream.of(
+ Arguments.of("stringVdmAttributes", "{\"VdmAttributes\": \"x\"}", EXPECTED_NULL),
+ Arguments.of("arrayVdmAttributes", "{\"VdmAttributes\": []}", LIST),
+ Arguments.of("booleanVdmEnabled", "{\"VdmAttributes\": {\"VdmEnabled\": true}}",
+ "TRUE_VALUE can not be converted to a String"),
+ Arguments.of("stringDashboardAttributes",
+ "{\"VdmAttributes\": {\"VdmEnabled\": \"ENABLED\", \"DashboardAttributes\": \"oops\"}}",
+ EXPECTED_NULL),
+ Arguments.of("numericOptimizedSharedDelivery", "{\"VdmAttributes\": {\"VdmEnabled\": \"ENABLED\", "
+ + "\"GuardianAttributes\": {\"OptimizedSharedDelivery\": 1}}}", NUMBER));
+ }
+
+ static Stream<Arguments> putAccountSuppressionAttributesCases() {
+ return Stream.of(
+ Arguments.of("stringSuppressedReasons", "{\"SuppressedReasons\": \"BOUNCE\"}", EXPECTED_LIST),
+ Arguments.of("numericReasons", "{\"SuppressedReasons\": [1, 2]}", NUMBER),
+ Arguments.of("objectReason", "{\"SuppressedReasons\": [{}]}", STRUCTURE),
+ Arguments.of("stringConditionThreshold",
+ "{\"ValidationAttributes\": {\"ConditionThreshold\": \"x\"}}", EXPECTED_NULL));
+ }
+
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("putAccountVdmAttributesCases")
+ void putAccountVdmAttributes_wrongMemberType(String caseName, String body, String message) {
+ assertSerializationException("PUT", VDM, body, message);
+ }
+
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("putAccountSuppressionAttributesCases")
+ void putAccountSuppressionAttributes_wrongMemberType(String caseName, String body, String message) {
+ assertSerializationException("PUT", SUPPRESSION, body, message);
+ }
+
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("nonObjectBodyPaths")
+ void nonObjectBody_isRejectedBeforeTheShapeCheck(String path) {
+ assertError("PUT", path, "[]", "BadRequestException", "Request body must be a JSON object.");
+ }
+
+ static Stream<String> nonObjectBodyPaths() {
+ return Stream.of(VDM, SUPPRESSION);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesAccountVdmV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesAccountVdmV2IntegrationTest.java
index 13b5b5b0c5..d8819fbd89 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesAccountVdmV2IntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesAccountVdmV2IntegrationTest.java
@@ -80,24 +80,6 @@ class SesAccountVdmV2IntegrationTest {
.body("__type", equalTo("BadRequestException"));
}
- @Test
- @Order(5)
- void putVdm_nonObjectDashboardAttributes_returnsBadRequest() {
- given().contentType("application/json").header("Authorization", AUTH)
- .body("{\"VdmAttributes\":{\"VdmEnabled\":\"ENABLED\",\"DashboardAttributes\":\"oops\"}}")
- .when().put("/v2/email/account/vdm").then().statusCode(400)
- .body("__type", equalTo("BadRequestException"));
- }
-
- @Test
- @Order(6)
- void putVdm_nonStringVdmEnabled_returnsBadRequest() {
- given().contentType("application/json").header("Authorization", AUTH)
- .body("{\"VdmAttributes\":{\"VdmEnabled\":true}}")
- .when().put("/v2/email/account/vdm").then().statusCode(400)
- .body("__type", equalTo("BadRequestException"));
- }
-
@Test
@Order(7)
void putVdm_enabledWithoutNested_defaultsNestedToDisabled() {
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesMetricsJobsMemberTypeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesMetricsJobsMemberTypeIntegrationTest.java
new file mode 100644
index 0000000000..ec20e86b4b
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesMetricsJobsMemberTypeIntegrationTest.java
@@ -0,0 +1,111 @@
+package io.github.hectorvent.floci.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.github.hectorvent.floci.services.ses.SesV2SerializationErrors.EXPECTED_LIST;
+import static io.github.hectorvent.floci.services.ses.SesV2SerializationErrors.EXPECTED_NULL;
+import static io.github.hectorvent.floci.services.ses.SesV2SerializationErrors.LIST;
+import static io.github.hectorvent.floci.services.ses.SesV2SerializationErrors.NUMBER;
+import static io.github.hectorvent.floci.services.ses.SesV2SerializationErrors.STRUCTURE;
+import static io.github.hectorvent.floci.services.ses.SesV2SerializationErrors.assertSerializationException;
+import static io.github.hectorvent.floci.services.ses.SesV2SerializationErrors.authFor;
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+
+/**
+ * BatchGetMetricData, CreateImportJob and CreateExportJob check their body against the SES v2
+ * shapes, so a member of the wrong JSON type, nested ones included, is a SerializationException
+ * ahead of the operation's own validation. BatchGetMetricData keeps its VDM gate in front of the
+ * check, so its cases run in a region of their own with VDM enabled.
+ */
+@QuarkusTest
+class SesMetricsJobsMemberTypeIntegrationTest {
+
+ private static final String VDM_REGION_AUTH = authFor("af-south-1");
+ private static final String VDM_OFF_REGION_AUTH = authFor("ap-east-1");
+ private static final String METRICS = "/v2/email/metrics/batch";
+ private static final String IMPORT = "/v2/email/import-jobs";
+ private static final String EXPORT = "/v2/email/export-jobs";
+
+ static Stream<Arguments> batchGetMetricDataCases() {
+ return Stream.of(
+ Arguments.of("objectQueries", "{\"Queries\": {}}", STRUCTURE),
+ Arguments.of("stringQueries", "{\"Queries\": \"x\"}", EXPECTED_LIST),
+ Arguments.of("stringQuery", "{\"Queries\": [\"x\"]}", EXPECTED_NULL),
+ Arguments.of("numericId", "{\"Queries\": [{\"Id\": 1}]}", NUMBER),
+ Arguments.of("arrayDimensions", "{\"Queries\": [{\"Dimensions\": []}]}", LIST),
+ Arguments.of("numericDimensionValue", "{\"Queries\": [{\"Dimensions\": {\"ISP\": 1}}]}", NUMBER));
+ }
+
+ static Stream<Arguments> createImportJobCases() {
+ return Stream.of(
+ Arguments.of("stringImportDataSource", "{\"ImportDataSource\": \"x\"}", EXPECTED_NULL),
+ Arguments.of("numericS3Url",
+ "{\"ImportDataSource\": {\"S3Url\": 1, \"DataFormat\": \"CSV\"}}", NUMBER),
+ Arguments.of("arrayImportDestination", "{\"ImportDestination\": []}", LIST),
+ Arguments.of("stringContactListDestination",
+ "{\"ImportDestination\": {\"ContactListDestination\": \"x\"}}", EXPECTED_NULL));
+ }
+
+ static Stream<Arguments> createExportJobCases() {
+ return Stream.of(
+ Arguments.of("stringExportDataSource", "{\"ExportDataSource\": \"x\"}", EXPECTED_NULL),
+ Arguments.of("stringMetricsDataSource",
+ "{\"ExportDataSource\": {\"MetricsDataSource\": \"x\"}}", EXPECTED_NULL),
+ Arguments.of("stringMetrics",
+ "{\"ExportDataSource\": {\"MetricsDataSource\": {\"Metrics\": \"SEND\"}}}", EXPECTED_LIST),
+ Arguments.of("arrayDimensions",
+ "{\"ExportDataSource\": {\"MetricsDataSource\": {\"Dimensions\": []}}}", LIST),
+ Arguments.of("numericDimensionValue",
+ "{\"ExportDataSource\": {\"MetricsDataSource\": {\"Dimensions\": {\"ISP\": [1]}}}}", NUMBER),
+ Arguments.of("objectIncludeFilter",
+ "{\"ExportDataSource\": {\"MessageInsightsDataSource\": {\"Include\": {\"Isp\": {}}}}}",
+ STRUCTURE),
+ Arguments.of("numericDataFormat", "{\"ExportDestination\": {\"DataFormat\": 1}}", NUMBER));
+ }
+
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("batchGetMetricDataCases")
+ void batchGetMetricData_wrongMemberType(String caseName, String body, String message) {
+ given()
+ .contentType("application/json")
+ .header("Authorization", VDM_REGION_AUTH)
+ .body("{\"VdmAttributes\": {\"VdmEnabled\": \"ENABLED\"}}")
+ .when()
+ .put("/v2/email/account/vdm")
+ .then()
+ .statusCode(200);
+ assertSerializationException(VDM_REGION_AUTH, "POST", METRICS, body, message);
+ }
+
+ @Test
+ void batchGetMetricData_vdmGateStaysAheadOfTheShapeCheck() {
+ given()
+ .contentType("application/json")
+ .header("Authorization", VDM_OFF_REGION_AUTH)
+ .body("{\"Queries\": \"x\"}")
+ .when()
+ .post(METRICS)
+ .then()
+ .statusCode(404)
+ .body("__type", equalTo("NotFoundException"));
+ }
+
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("createImportJobCases")
+ void createImportJob_wrongMemberType(String caseName, String body, String message) {
+ assertSerializationException("POST", IMPORT, body, message);
+ }
+
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("createExportJobCases")
+ void createExportJob_wrongMemberTypeBeforeTheDataSourceCheck(String caseName, String body, String message) {
+ assertSerializationException("POST", EXPORT, body, message);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2IntegrationTest.java
index d83b1d9fa7..110f488222 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesV2IntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2IntegrationTest.java
@@ -774,22 +774,6 @@ class SesV2IntegrationTest {
+ "Member must satisfy constraint: [Member must satisfy enum value set: [BOUNCE, COMPLAINT]]"));
}
- @Test
- @Order(63)
- void putAccountSuppressionAttributes_reasonsNotArray_returns400() {
- given()
- .contentType("application/json")
- .header("Authorization", AUTH_HEADER)
- .body("""
- {"SuppressedReasons": "BOUNCE"}
- """)
- .when()
- .put("/v2/email/account/suppression")
- .then()
- .statusCode(400)
- .body("__type", equalTo("BadRequestException"));
- }
-
@Test
@Order(64)
void putAccountSuppressionAttributes_nullMember_returns400() {
@@ -806,22 +790,6 @@ class SesV2IntegrationTest {
.body("__type", equalTo("BadRequestException"));
}
- @Test
- @Order(65)
- void putAccountSuppressionAttributes_numericMember_returns400() {
- given()
- .contentType("application/json")
- .header("Authorization", AUTH_HEADER)
- .body("""
- {"SuppressedReasons": [1, 2]}
- """)
- .when()
- .put("/v2/email/account/suppression")
- .then()
- .statusCode(400)
- .body("__type", equalTo("BadRequestException"));
- }
-
@Test
@Order(66)
void putAccountSuppressionAttributes_acceptsValidationAttributes() {
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesV2SerializationErrors.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2SerializationErrors.java
index f80039e2ee..ce74053d70 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesV2SerializationErrors.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2SerializationErrors.java
@@ -11,7 +11,7 @@ import static org.hamcrest.Matchers.equalTo;
*/
final class SesV2SerializationErrors {
- static final String AUTH = "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request";
+ static final String AUTH = authFor("us-east-1");
static final String STRUCTURE = "Start of structure or map found where not expected.";
static final String LIST = "Start of list found where not expected";
static final String NUMBER = "NUMBER_VALUE can not be converted to a String";
@@ -21,10 +21,19 @@ final class SesV2SerializationErrors {
private SesV2SerializationErrors() {
}
+ /** An Authorization header signed for {@code region}, for a test that needs its own region state. */
+ static String authFor(String region) {
+ return "AWS4-HMAC-SHA256 Credential=AKID/20260101/" + region + "/email/aws4_request";
+ }
+
static void assertError(String method, String path, String body, String type, String message) {
+ assertError(AUTH, method, path, body, type, message);
+ }
+
+ static void assertError(String auth, String method, String path, String body, String type, String message) {
given()
.contentType("application/json")
- .header("Authorization", AUTH)
+ .header("Authorization", auth)
.body(body)
.when()
.request(method, path)
@@ -37,4 +46,9 @@ final class SesV2SerializationErrors {
static void assertSerializationException(String method, String path, String body, String message) {
assertError(method, path, body, "SerializationException", message);
}
+
+ static void assertSerializationException(String auth, String method, String path, String body,
+ String message) {
+ assertError(auth, method, path, body, "SerializationException", message);
+ }
}