fix(ses): check v2 send request bodies against the service model (#5765)

* fix(ses): check v2 send request bodies against the service model

SendEmail, SendBulkEmail and SendCustomVerificationEmail read their
members by hand, so a member of the wrong JSON type was coerced, read as
empty, or rejected with a Floci-specific BadRequestException, depending
on which member it was. AWS deserializes the whole body against the
model first and answers the first member of the wrong type, in body
order, with a SerializationException and its deserializer message.

tools/aws/regen_sesv2_shapes.py vendors the body shapes of botocore's
SES v2 model into src/main/resources/aws/sesv2-request-shapes.json, kept
in sync by make aws-data-check like the DynamoDB shapes.
SesV2RequestShapes checks a body against them, and the three send
endpoints call it before reading any member. The type checks it makes
redundant are removed from the send helpers. A null address list
element still passes and fails as "Invalid email address null.", as on
AWS.

Only the string, blob, list, structure and map messages have been
probed, so number, boolean and timestamp members are left to their
controllers.

* fix(ses): report a null v2 send address where SES does

A null element of a v2 send address list was rejected for the whole
request while the body was read. SES lets it through deserialization
and reports it later: 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.

The address lists now keep the null, SendEmail checks for it ahead of
the tenant gate, and the bulk entry check reports it per entry. Two
ordered integration tests that shared an @Order value get their own.

* chore(core): share the vendored request-shape model

DynamoDbRequestShapes and SesV2RequestShapes each carried the same
Shape and Model records and the same parse() and load(), and load()
repeated VendoredResources.read. RequestShapeModel in core.common now
holds that half and both checks use it; each keeps its own walk and its
protocol's messages.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-10-16 06:46:25 -04:00
1 parent 0a5809a559
commit e24a2882bc
22 files changed
+2853 -219

No files matched your search

+9
View File
@@ -17,6 +17,8 @@
# src/main/resources/aws/redshift-serverless-request-shapes.json is generated from botocore's Redshift
# Serverless model by tools/aws/regen_redshift_serverless_shapes.py.
# API Gateway integration types come from the public service model via tools/aws/regen_apigateway_types.py.
# src/main/resources/aws/sesv2-request-shapes.json is generated from botocore's SES v2 model
# by tools/aws/regen_sesv2_shapes.py.
PYTHON ?= python3
@@ -209,6 +211,7 @@ aws-data-sync: ## Regenerate src/main/resources/aws/*.json and the IAM managed-p
$(PYTHON) tools/aws/regen_dynamodb_shapes.py
$(PYTHON) tools/aws/regen_redshift_serverless_shapes.py
$(PYTHON) tools/aws/regen_apigateway_types.py
$(PYTHON) tools/aws/regen_sesv2_shapes.py
$(PYTHON) tools/aws/regen_managed_policies.py
aws-data-check: ## CI gate: the vendored AWS data must match a fresh generation
@@ -240,6 +243,12 @@ aws-data-check: ## CI gate: the vendored AWS data must match a fresh generation
echo "error: API Gateway integration types are out of date; run 'make aws-data-sync'."; \
exit 1; \
}
@$(PYTHON) tools/aws/regen_sesv2_shapes.py --check || { \
echo ""; \
echo "error: src/main/resources/aws/sesv2-request-shapes.json is out of date."; \
echo " Run 'make aws-data-sync' and commit the result."; \
exit 1; \
}
@$(PYTHON) tools/aws/regen_managed_policies.py --check || { \
echo ""; \
echo "error: the IAM managed-policy catalog (src/main/resources/iam/managed-polic*) is out of date or malformed."; \
+15
View File
@@ -501,6 +501,21 @@ registered Easy DKIM domain do not report this SES-hosted zone.
S/MIME certificate associations are stored per region and never used: Floci does not sign mail. Associating validates the request as SES does (a domain identity needs a `FromAddress` in the domain or one of its subdomains, one certificate per address regardless of case) but, like SES, does not inspect the certificate. `ListEmailIdentityCertificates` reports `ACTIVE` while the association meets the [S/MIME certificate considerations](https://docs.aws.amazon.com/ses/latest/dg/send-email-authentication-smime.html#send-email-authentication-smime-certificate-considerations), plus the requirements a probe found SES also enforces (an end-entity certificate whose key usage includes `digitalSignature` and whose extended key usage includes `emailProtection`), checked against Floci's ACM and identity verification when the list is read, with the certificate's expiry as `CertificateExpiryTime`, and `FAILED` otherwise. There is no `PROVISIONING` phase, `DisassociateEmailIdentityCertificate` removes an association at once, and the certificate is not listed as in use by ACM. As on SES, `DeleteEmailIdentity` refuses an identity that still has a certificate associated, whatever its status. The v1 `DeleteIdentity` and `DeleteVerifiedEmailAddress` share the identities and refuse it too, with the same `BadRequestException` the tenant-association guard returns there; SES's v1 behaviour was not probed.
### Request member types
The send operations (`SendEmail`, `SendBulkEmail`, `SendCustomVerificationEmail`) check the request body against the SES v2 service model before anything else is validated, as AWS's restJson1 deserializer does. 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 |
|---|---|---|
| string, blob | number or boolean | `NUMBER_VALUE can not be converted to a String` (`TRUE_VALUE` / `FALSE_VALUE`; `a Blob` for a blob) |
| string, blob | object / array | `Start of structure or map found where not expected.` / `Start of list found where not expected` |
| 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. The account-level sending switch is still checked first, so a paused account answers `SendingPausedException` even for a malformed body.
The body shapes are vendored in `src/main/resources/aws/sesv2-request-shapes.json`, generated by `tools/aws/regen_sesv2_shapes.py` from the botocore release pinned in `tools/aws/requirements.txt`.
### IAM enforcement
With `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`, every SES v2 operation is authorized as the `ses:`
@@ -0,0 +1,44 @@
package io.github.hectorvent.floci.core.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* The input shapes of a service's operations, as a {@code tools/aws/regen_*_shapes.py} generator
* vendors them from botocore: each operation's input shape, and for every shape reachable from one
* its type and the shapes of its structure members, list elements or map values. A service's
* request check walks a body against it with its own protocol's messages.
*/
public record RequestShapeModel(Map<String, String> operations, Map<String, Shape> shapes) {
private static final ObjectMapper MAPPER = new ObjectMapper();
/** One shape: its type, the shape of each structure member, or the list element or map value shape. */
public record Shape(String type, Map<String, String> members, String element) {
}
/** The vendored resource {@code name}; {@code description} names it in a failure. */
public static RequestShapeModel load(String name, String description) {
return VendoredResources.read(name, description, in -> parse(MAPPER.readTree(in)));
}
public static RequestShapeModel parse(JsonNode root) {
Map<String, String> operations = new HashMap<>();
root.path("operations").properties().forEach(op -> operations.put(op.getKey(), op.getValue().asText()));
Map<String, Shape> shapes = new HashMap<>();
for (Map.Entry<String, JsonNode> entry : root.path("shapes").properties()) {
JsonNode node = entry.getValue();
Map<String, String> members = new LinkedHashMap<>();
node.path("members").properties().forEach(m -> members.put(m.getKey(), m.getValue().asText()));
String element = node.hasNonNull("member") ? node.get("member").asText() : node.path("value").asText(null);
shapes.put(entry.getKey(), new Shape(node.path("type").asText(), Collections.unmodifiableMap(members),
element));
}
return new RequestShapeModel(Map.copyOf(operations), Map.copyOf(shapes));
}
}
@@ -1,14 +1,11 @@
package io.github.hectorvent.floci.services.dynamodb;
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.core.common.RequestShapeModel;
import io.github.hectorvent.floci.core.common.RequestShapeModel.Shape;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
/**
@@ -24,21 +21,13 @@ public final class DynamoDbRequestShapes {
static final String RESOURCE_NAME = "aws/dynamodb-request-shapes.json";
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String OBJECT_NOT_EXPECTED = "Start of structure or map found where not expected";
private static final String UNKNOWN_ERROR = "UnknownError";
private static final String UNEXPECTED_FIELD_TYPE = "Unexpected field type";
private static final String UNEXPECTED_VALUE_TYPE = "Unexpected value type in payload";
record Shape(String type, Map<String, String> members, String element) {
}
record Model(Map<String, String> operations, Map<String, Shape> shapes) {
}
private static final class Holder {
static final Model MODEL = load();
static final RequestShapeModel MODEL = RequestShapeModel.load(RESOURCE_NAME, "DynamoDB request shapes");
}
private DynamoDbRequestShapes() {
@@ -49,14 +38,14 @@ public final class DynamoDbRequestShapes {
check(Holder.MODEL, action, request);
}
static void check(Model model, String action, JsonNode request) {
static void check(RequestShapeModel model, String action, JsonNode request) {
String input = model.operations().get(action);
if (input != null) {
checkValue(model, model.shapes().get(input), request, true);
}
}
private static void checkValue(Model model, Shape shape, JsonNode value, boolean member) {
private static void checkValue(RequestShapeModel model, Shape shape, JsonNode value, boolean member) {
if (value.isNull()) {
return;
}
@@ -68,7 +57,7 @@ public final class DynamoDbRequestShapes {
}
}
private static void checkStructure(Model model, Shape shape, JsonNode value, boolean member) {
private static void checkStructure(RequestShapeModel model, Shape shape, JsonNode value, boolean member) {
if (value.isArray()) {
throw serialization(UNKNOWN_ERROR);
}
@@ -85,7 +74,7 @@ public final class DynamoDbRequestShapes {
}
}
private static void checkList(Model model, Shape shape, JsonNode value, boolean member) {
private static void checkList(RequestShapeModel model, Shape shape, JsonNode value, boolean member) {
if (value.isObject()) {
throw serialization(OBJECT_NOT_EXPECTED);
}
@@ -98,7 +87,7 @@ public final class DynamoDbRequestShapes {
}
}
private static void checkMap(Model model, Shape shape, JsonNode value, boolean member) {
private static void checkMap(RequestShapeModel model, Shape shape, JsonNode value, boolean member) {
if (value.isArray()) {
throw serialization(UNKNOWN_ERROR);
}
@@ -168,31 +157,4 @@ public final class DynamoDbRequestShapes {
private static AwsException serialization(String message) {
return new AwsException("SerializationException", message, 400);
}
private static Model load() {
try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(RESOURCE_NAME)) {
if (in == null) {
throw new IllegalStateException("DynamoDB request shape resource not found: " + RESOURCE_NAME);
}
return parse(MAPPER.readTree(in));
} catch (IOException e) {
throw new IllegalStateException("Failed to read the DynamoDB request shapes " + RESOURCE_NAME, e);
}
}
static Model parse(JsonNode root) {
Map<String, String> operations = new HashMap<>();
root.path("operations").fields().forEachRemaining(op -> operations.put(op.getKey(), op.getValue().asText()));
Map<String, Shape> shapes = new HashMap<>();
Iterator<Map.Entry<String, JsonNode>> entries = root.path("shapes").fields();
while (entries.hasNext()) {
Map.Entry<String, JsonNode> entry = entries.next();
JsonNode node = entry.getValue();
Map<String, String> members = new LinkedHashMap<>();
node.path("members").fields().forEachRemaining(m -> members.put(m.getKey(), m.getValue().asText()));
String element = node.hasNonNull("member") ? node.get("member").asText() : node.path("value").asText(null);
shapes.put(entry.getKey(), new Shape(node.path("type").asText(), members, element));
}
return new Model(operations, shapes);
}
}
@@ -39,13 +39,9 @@ import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Objects;
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;
/**
* REST JSON controller for the three SES V2 send endpoints:
@@ -96,13 +92,14 @@ public class SesSendController {
JsonNode request = objectMapper.readTree(body);
requireJsonObject(request);
SesV2RequestShapes.check("SendEmail", request);
// FromEmailAddress is optional per the AWS v2 contract. Each content type below
// enforces the sender requirement the way AWS does: Raw can take its From from the
// MIME message, while Simple and Templated require FromEmailAddress.
String fromEmailAddress = request.path("FromEmailAddress").asText(null);
JsonNode destination = requireObjectOrAbsent(request, "Destination");
JsonNode destination = request.path("Destination");
List<String> toAddresses = addressList(destination, "ToAddresses");
List<String> ccAddresses = addressList(destination, "CcAddresses");
List<String> bccAddresses = addressList(destination, "BccAddresses");
@@ -113,7 +110,7 @@ public class SesSendController {
// and X-SES-FROM-ARN headers", so it stands for both ARNs of a raw send.
String fromIdentityArn = request.path("FromEmailAddressIdentityArn").asText(null);
String configurationSetName = request.path("ConfigurationSetName").asText(null);
String tenantName = stringMemberOrAbsent(request, "TenantName");
String tenantName = request.path("TenantName").asText(null);
List<MessageTag> emailTags = parseEmailTagsArray(request.path("EmailTags"), "EmailTags");
ListManagementOptions listManagement =
parseListManagementOptions(request.path("ListManagementOptions"));
@@ -142,6 +139,7 @@ public class SesSendController {
throw new AwsException("BadRequestException",
"Content.Raw.Data is required.", 400);
}
requireNoNullAddress(toAddresses, ccAddresses, bccAddresses, replyToAddresses);
SendEmailRequest rawRequest = sendRequest.content(new EmailContent.Raw(rawData, true)).build();
sesService.checkTenantRawSendAccess(tenantName, fromEmailAddress, rawData,
rawRequest.hasRecipients(), configurationSetName, regionResolver.getAccountId(), region);
@@ -159,6 +157,7 @@ public class SesSendController {
parseHeadersArray(simple.path("Headers"), "content.simple.headers");
List<MessageAttachment> attachments =
parseAttachmentsArray(simple.path("Attachments"), "content.simple.attachments");
requireNoNullAddress(toAddresses, ccAddresses, bccAddresses, replyToAddresses);
sesService.checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName,
null, regionResolver.getAccountId(), region);
messageId = sesService.sendEmail(sendRequest
@@ -192,6 +191,7 @@ public class SesSendController {
String resolvedName = hasName
? templateName
: SesTemplateService.templateNameFromArn(templateArn);
requireNoNullAddress(toAddresses, ccAddresses, bccAddresses, replyToAddresses);
sesService.checkTenantSendAccess(tenantName, fromEmailAddress,
configurationSetName, resolvedName, regionResolver.getAccountId(), region);
messageId = sesService.sendEmail(sendRequest
@@ -206,6 +206,7 @@ public class SesSendController {
// inline content is not a stored template resource, so only the identity and
// configuration set pass through the gate.
SesService.requireInlineTemplateContent(subject, text, html);
requireNoNullAddress(toAddresses, ccAddresses, bccAddresses, replyToAddresses);
sesService.checkTenantSendAccess(tenantName, fromEmailAddress,
configurationSetName, null, regionResolver.getAccountId(), region);
messageId = sesService.sendEmail(sendRequest
@@ -243,6 +244,7 @@ public class SesSendController {
JsonNode request = objectMapper.readTree(body);
requireJsonObject(request);
SesV2RequestShapes.check("SendBulkEmail", request);
String fromEmailAddress = request.path("FromEmailAddress").asText(null);
if (fromEmailAddress == null || fromEmailAddress.isBlank()) {
throw new AwsException("BadRequestException",
@@ -254,7 +256,7 @@ public class SesSendController {
request.path("FeedbackForwardingEmailAddress").asText(null);
SesAddressSyntax.requireBulkAddress(feedbackForwardingAddress);
String configurationSetName = request.path("ConfigurationSetName").asText(null);
String tenantName = stringMemberOrAbsent(request, "TenantName");
String tenantName = request.path("TenantName").asText(null);
JsonNode template = request.path("DefaultContent").path("Template");
if (template.isMissingNode() || template.isNull()) {
@@ -319,12 +321,11 @@ public class SesSendController {
throw new AwsException("BadRequestException",
"BulkEmailEntries elements must be JSON objects.", 400);
}
JsonNode dest = requireObjectOrAbsent(node, "Destination");
JsonNode dest = node.path("Destination");
List<String> to = addressList(dest, "ToAddresses");
List<String> cc = addressList(dest, "CcAddresses");
List<String> bcc = addressList(dest, "BccAddresses");
JsonNode replacementContent = requireObjectOrAbsent(node, "ReplacementEmailContent");
JsonNode replacementTemplate = requireObjectOrAbsent(replacementContent, "ReplacementTemplate");
JsonNode replacementTemplate = node.path("ReplacementEmailContent").path("ReplacementTemplate");
JsonNode replacementData = parseTemplateData(replacementTemplate, "ReplacementTemplateData");
List<MessageTag> replacementTags = parseEmailTagsArray(node.path("ReplacementTags"), "ReplacementTags");
List<MessageHeader> entryReplacementHeaders = parseHeadersArray(node.path("ReplacementHeaders"),
@@ -389,6 +390,7 @@ public class SesSendController {
}
JsonNode request = objectMapper.readTree(body);
requireJsonObject(request);
SesV2RequestShapes.check("SendCustomVerificationEmail", request);
templateName = request.path("TemplateName").asText(null);
String messageId = sesService.sendCustomVerificationEmail(
request.path("EmailAddress").asText(null), templateName,
@@ -411,29 +413,29 @@ public class SesSendController {
// ──────────────────────────── Helpers ────────────────────────────
// A present address list of the wrong JSON type, or with a non-string element, is rejected
// rather than read as empty or coerced.
// A null element passes deserialization on AWS and is kept: it fails later as an invalid
// address, after the content and sender checks (probe-confirmed).
private static List<String> addressList(JsonNode parent, String field) {
return Objects.requireNonNullElse(stringArrayOrAbsent(parent, field), List.of());
List<String> addresses = new ArrayList<>();
for (JsonNode item : parent.path(field)) {
addresses.add(item.isNull() ? null : item.textValue());
}
return addresses;
}
// On SendEmail a null address is reported after the content and sender checks and before the
// tenant lookup (probe-confirmed).
@SafeVarargs
private static void requireNoNullAddress(List<String>... lists) {
for (List<String> addresses : lists) {
if (addresses.contains(null)) {
throw new AwsException("BadRequestException", "Invalid email address null.", 400);
}
}
}
private JsonNode parseTemplateData(JsonNode parent, String fieldName) {
if (parent == null || parent.isMissingNode() || parent.isNull()) {
return objectMapper.createObjectNode();
}
if (!parent.isObject()) {
throw new AwsException("BadRequestException",
"Parent of " + fieldName + " must be a JSON object.", 400);
}
JsonNode field = parent.path(fieldName);
if (field.isMissingNode() || field.isNull()) {
return objectMapper.createObjectNode();
}
if (!field.isTextual()) {
throw new AwsException("BadRequestException",
fieldName + " must be a JSON-encoded string.", 400);
}
return parseTemplateData(field.asText(""));
return parseTemplateData(parent.path(fieldName).asText(null));
}
private JsonNode parseTemplateData(String raw) {
@@ -463,12 +465,6 @@ public class SesSendController {
* {@code content.simple.headers}) and the offending 1-based index.
*/
private List<MessageHeader> parseHeadersArray(JsonNode headersNode, String location) {
if (headersNode.isMissingNode() || headersNode.isNull()) {
return List.of();
}
if (!headersNode.isArray()) {
throw new AwsException("BadRequestException", "Headers must be an array.", 400);
}
List<MessageHeader> out = new ArrayList<>();
int index = 1;
for (JsonNode h : headersNode) {
@@ -502,12 +498,6 @@ public class SesSendController {
* message anchored at {@code location} and the offending 1-based index, as for headers.
*/
private List<MessageAttachment> parseAttachmentsArray(JsonNode attachmentsNode, String location) {
if (attachmentsNode.isMissingNode() || attachmentsNode.isNull()) {
return List.of();
}
if (!attachmentsNode.isArray()) {
throw new AwsException("BadRequestException", "Attachments must be an array.", 400);
}
List<MessageAttachment> out = new ArrayList<>();
int index = 1;
for (JsonNode node : attachmentsNode) {
@@ -524,10 +514,6 @@ public class SesSendController {
if (rawNode == null || rawNode.isNull()) {
throw constraintViolation(null, memberPrefix + "rawContent", "Member must not be null");
}
if (!rawNode.isTextual()) {
throw new AwsException("BadRequestException",
"RawContent must be a base64-encoded string.", 400);
}
byte[] rawContent;
try {
rawContent = Base64.getDecoder().decode(rawNode.textValue());
@@ -556,9 +542,6 @@ public class SesSendController {
if (value == null || value.isNull()) {
return null;
}
if (!value.isTextual()) {
throw new AwsException("BadRequestException", member + " must be a string.", 400);
}
String text = value.textValue();
if (text.length() < min) {
throw constraintViolation(text, path, "Member must have length greater than or equal to " + min);
@@ -610,27 +593,15 @@ public class SesSendController {
}
private static ListManagementOptions parseListManagementOptions(JsonNode node) {
if (node == null || node.isMissingNode() || node.isNull()) {
if (node.isMissingNode() || node.isNull()) {
return null;
}
if (!node.isObject()) {
throw new AwsException("BadRequestException", "ListManagementOptions must be an object.", 400);
}
JsonNode listNode = node.path("ContactListName");
if (!listNode.isTextual() || listNode.textValue().isBlank()) {
throw new AwsException("BadRequestException",
"ListManagementOptions.ContactListName is required.", 400);
}
JsonNode topicNode = node.path("TopicName");
String topicName = null;
if (!topicNode.isMissingNode() && !topicNode.isNull()) {
if (!topicNode.isTextual()) {
throw new AwsException("BadRequestException",
"ListManagementOptions.TopicName must be a string.", 400);
}
topicName = topicNode.textValue();
}
return new ListManagementOptions(listNode.textValue(), topicName);
return new ListManagementOptions(listNode.textValue(), node.path("TopicName").asText(null));
}
/**
@@ -640,16 +611,10 @@ public class SesSendController {
* 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.
* The {@code fieldName} parameter is reported in the error message when an element is
* null.
*/
private List<MessageTag> parseEmailTagsArray(JsonNode tagsNode, String fieldName) {
if (tagsNode.isMissingNode() || tagsNode.isNull()) {
return List.of();
}
if (!tagsNode.isArray()) {
throw new AwsException("BadRequestException", fieldName + " must be an array.", 400);
}
List<MessageTag> out = new ArrayList<>();
for (JsonNode t : tagsNode) {
if (!t.isObject()) {
@@ -49,8 +49,10 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Stream;
/**
* What is left of the original single SES service after the store-based domain split and the
@@ -1680,10 +1682,11 @@ public class SesService {
}
}
boolean requestHasRecipient = request.entries().stream().anyMatch(SesService::hasNonNullRecipient);
List<BulkEmailEntryResult> results = new ArrayList<>(request.entries().size());
for (BulkEmailEntry entry : request.entries()) {
try {
SesAddressSyntax.requireBulkDestination(entry, request.replyToAddresses());
SesAddressSyntax.requireBulkDestination(entry, request.replyToAddresses(), requestHasRecipient);
JsonNode merged = mergeTemplateData(template.templateData(), entry.replacementTemplateData());
List<MessageTag> mergedTags = mergeEmailTags(request.defaultEmailTags(), entry.replacementEmailTags());
List<MessageHeader> mergedHeaders = mergeHeaders(template.headers(), entry.replacementHeaders());
@@ -1720,6 +1723,13 @@ public class SesService {
return results;
}
private static boolean hasNonNullRecipient(BulkEmailEntry entry) {
return Stream.of(entry.toAddresses(), entry.ccAddresses(), entry.bccAddresses())
.filter(Objects::nonNull)
.flatMap(List::stream)
.anyMatch(Objects::nonNull);
}
private static List<String> headerText(List<MessageHeader> headers) {
if (headers == null) {
return List.of();
@@ -159,7 +159,7 @@ final class SesV2Json {
if (node.isArray()) {
throw unexpectedStartError(node);
}
throw new AwsException("SerializationException", "Expected null", 400);
throw expectedNullError();
}
/** A string member with the AWS deserializer's message for each wrong JSON type. */
@@ -171,16 +171,7 @@ final class SesV2Json {
if (node.isTextual()) {
return node.textValue();
}
if (node.isNumber()) {
throw new AwsException("SerializationException",
"NUMBER_VALUE can not be converted to a String", 400);
}
if (node.isBoolean()) {
throw new AwsException("SerializationException",
(node.booleanValue() ? "TRUE_VALUE" : "FALSE_VALUE")
+ " can not be converted to a String", 400);
}
throw unexpectedStartError(node);
throw scalarTypeError(node, "String");
}
/**
@@ -229,6 +220,33 @@ final class SesV2Json {
return values;
}
/**
* The deserializer's message for a scalar member of type {@code target} (such as
* {@code "String"}, {@code "Blob"} or {@code "Boolean"}) given a value of another JSON type.
*/
static AwsException scalarTypeError(JsonNode node, String target) {
if (node.isNumber()) {
return new AwsException("SerializationException",
"NUMBER_VALUE can not be converted to a " + target, 400);
}
if (node.isBoolean()) {
return new AwsException("SerializationException",
(node.booleanValue() ? "TRUE_VALUE" : "FALSE_VALUE") + " can not be converted to a " + target,
400);
}
return unexpectedStartError(node);
}
/** The deserializer's message for a structure or map member given a scalar. */
static AwsException expectedNullError() {
return new AwsException("SerializationException", "Expected null", 400);
}
/** The deserializer's message for a list member given a scalar. */
static AwsException expectedListError() {
return new AwsException("SerializationException", "Expected list or null", 400);
}
static AwsException unexpectedStartError(JsonNode node) {
if (node.isArray()) {
return new AwsException("SerializationException",
@@ -0,0 +1,113 @@
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.RequestShapeModel;
import io.github.hectorvent.floci.core.common.RequestShapeModel.Shape;
import org.jboss.logging.Logger;
import java.util.Map;
/**
* Rejects an SES v2 request body member of the wrong JSON type with the SerializationException
* SES answers before it validates anything. The body shapes come from the vendored
* {@code aws/sesv2-request-shapes.json}, generated from botocore's SES v2 model by
* {@code tools/aws/regen_sesv2_shapes.py}.
*
* <p>AWS reads the body in order and reports the first bad member, without naming it. A JSON null
* counts as an absent member, a null list element is left to the operation's own validation, and
* a member the model does not know is ignored. A map container answers like a structure, as the
* list operations' {@code Filter} already does. Only the string, blob, list and structure messages
* have been probed, so a number, boolean or timestamp member is still checked by its controller.
* The probes sent integers only: a non-integral number is reported as {@code NUMBER_VALUE} too,
* although AWS may name it differently.
*/
final class SesV2RequestShapes {
static final String RESOURCE_NAME = "aws/sesv2-request-shapes.json";
private static final Logger LOG = Logger.getLogger(SesV2RequestShapes.class);
private static final class Holder {
static final RequestShapeModel MODEL = RequestShapeModel.load(RESOURCE_NAME, "SES v2 request shapes");
}
private SesV2RequestShapes() {
}
/** Checks an SES v2 request body against the body shape of {@code operation}. */
static void check(String operation, JsonNode request) {
check(Holder.MODEL, operation, request);
}
static void check(RequestShapeModel model, String operation, JsonNode request) {
String input = model.operations().get(operation);
if (input == null) {
LOG.errorv("No SES v2 input shape for operation {0} in {1}", operation, RESOURCE_NAME);
throw new AwsException("InternalFailure",
"The request processing has failed because of an unknown error.", 500);
}
checkValue(model, model.shapes().get(input), request);
}
private static void checkValue(RequestShapeModel model, Shape shape, JsonNode value) {
if (value.isNull()) {
return;
}
switch (shape.type()) {
case "structure" -> checkStructure(model, shape, value);
case "map" -> checkMap(model, shape, value);
case "list" -> checkList(model, shape, value);
case "string" -> checkScalar(value, "String");
case "blob" -> checkScalar(value, "Blob");
default -> {
}
}
}
private static void checkStructure(RequestShapeModel model, Shape shape, JsonNode value) {
requireObject(value);
for (Map.Entry<String, JsonNode> field : value.properties()) {
String memberShape = shape.members().get(field.getKey());
if (memberShape != null) {
checkValue(model, model.shapes().get(memberShape), field.getValue());
}
}
}
private static void checkMap(RequestShapeModel model, Shape shape, JsonNode value) {
requireObject(value);
Shape element = model.shapes().get(shape.element());
for (JsonNode item : value) {
checkValue(model, element, item);
}
}
private static void checkList(RequestShapeModel model, Shape shape, JsonNode value) {
if (value.isObject()) {
throw SesV2Json.unexpectedStartError(value);
}
if (!value.isArray()) {
throw SesV2Json.expectedListError();
}
Shape element = model.shapes().get(shape.element());
for (JsonNode item : value) {
checkValue(model, element, item);
}
}
private static void requireObject(JsonNode value) {
if (value.isArray()) {
throw SesV2Json.unexpectedStartError(value);
}
if (!value.isObject()) {
throw SesV2Json.expectedNullError();
}
}
private static void checkScalar(JsonNode value, String target) {
if (!value.isTextual()) {
throw SesV2Json.scalarTypeError(value, target);
}
}
}
@@ -31,6 +31,8 @@ public final class SesAddressSyntax {
private static final List<String> RAW_CHECKED_HEADERS = List.of("To", "Cc", "Bcc");
private static final String MISSING_FINAL_DOMAIN = "Missing final '@domain'";
private static final String NULL_ADDRESS = "Invalid email address null.";
private static final String EMPTY_DESTINATION = "Destination cannot be empty";
private static final String PHRASE_SPECIALS = "()<>@,;:\\\".[]";
private static final String ADDRESS_SPECIALS = "()<>,;:\\\"[]";
@@ -195,13 +197,29 @@ public final class SesAddressSyntax {
* malformed entry recipient as that entry's status, and a malformed Reply-To as the status of
* every entry, not as a request error (probe-confirmed). An address list of the wrong JSON type
* never reaches this check: the controller rejects the whole request with SerializationException.
*
* <p>A null element passes deserialization and fails here as "Invalid email address null.",
* unless no entry of the request has a non-null recipient: then an entry holding one answers
* "Destination cannot be empty" (probe-confirmed for To lists of nulls; how SES words an entry
* whose lists are merely empty was not probed, so that case is left as it was).
*/
public static void requireBulkDestination(BulkEmailEntry entry, List<String> replyToAddresses) {
for (List<String> addresses : Arrays.asList(entry.toAddresses(), entry.ccAddresses(), entry.bccAddresses(),
replyToAddresses)) {
if (addresses != null) {
addresses.forEach(SesAddressSyntax::require);
public static void requireBulkDestination(BulkEmailEntry entry, List<String> replyToAddresses,
boolean requestHasRecipient) {
for (List<String> addresses : Arrays.asList(entry.toAddresses(), entry.ccAddresses(), entry.bccAddresses())) {
requireBulkAddresses(addresses, requestHasRecipient ? NULL_ADDRESS : EMPTY_DESTINATION);
}
requireBulkAddresses(replyToAddresses, NULL_ADDRESS);
}
private static void requireBulkAddresses(List<String> addresses, String nullMessage) {
if (addresses == null) {
return;
}
for (String address : addresses) {
if (address == null) {
throw new AwsException("InvalidParameterValue", nullMessage, 400);
}
require(address);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,71 @@
package io.github.hectorvent.floci.core.common;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.RequestShapeModel.Shape;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RequestShapeModelTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@Test
void parseReadsOperationsAndEachShapeKind() throws Exception {
RequestShapeModel model = RequestShapeModel.parse(MAPPER.readTree("""
{
"_source": {"generator": "test"},
"operations": {"Send": "SendRequest"},
"shapes": {
"SendRequest": {"type": "structure", "members": {"To": "Addresses", "Tags": "TagMap", "From": "Address"}},
"Addresses": {"type": "list", "member": "Address"},
"TagMap": {"type": "map", "value": "Address"},
"Address": {"type": "string"}
}
}
"""));
assertEquals(Map.of("Send", "SendRequest"), model.operations());
Shape request = model.shapes().get("SendRequest");
assertEquals("structure", request.type());
assertEquals(List.of("To", "Tags", "From"), List.copyOf(request.members().keySet()));
assertEquals("Address", model.shapes().get("Addresses").element());
assertEquals("Address", model.shapes().get("TagMap").element());
Shape scalar = model.shapes().get("Address");
assertEquals("string", scalar.type());
assertTrue(scalar.members().isEmpty());
assertNull(scalar.element());
}
@Test
void loadReadsAClasspathResource() {
RequestShapeModel model = RequestShapeModel.load("fixtures/core/request-shapes.json", "Test request shapes");
assertEquals("SendRequest", model.operations().get("Send"));
assertEquals("Address", model.shapes().get("Addresses").element());
}
@Test
void parsedModelCannotBeChanged() {
RequestShapeModel model = RequestShapeModel.load("fixtures/core/request-shapes.json", "Test request shapes");
assertThrows(UnsupportedOperationException.class, () -> model.operations().put("Other", "SendRequest"));
assertThrows(UnsupportedOperationException.class, () -> model.shapes().remove("Address"));
assertThrows(UnsupportedOperationException.class,
() -> model.shapes().get("SendRequest").members().put("Cc", "Addresses"));
}
@Test
void loadFailsForAMissingResource() {
IllegalStateException error = assertThrows(IllegalStateException.class,
() -> RequestShapeModel.load("aws/no-such-shapes.json", "Test request shapes"));
assertEquals("Test request shapes resource not found: aws/no-such-shapes.json", error.getMessage());
}
}
@@ -332,6 +332,21 @@ class SesBulkV2IntegrationTest {
.body("__type", equalTo("BadRequestException"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("wrongTypeSendBulkEmailBodies")
@Order(12)
void sendBulkEmail_wrongMemberType_returnsSerializationException(String label, String body) {
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
.body(body)
.when()
.post("/v2/email/outbound-bulk-emails")
.then()
.statusCode(400)
.body("__type", equalTo("SerializationException"));
}
static Stream<Arguments> malformedSendBulkEmailBodies() {
String validDefaultTemplate = "\"DefaultContent\": {\"Template\": {\"TemplateName\": \"v2-bulk-welcome\", \"TemplateData\": \"{\\\"team\\\":\\\"floci\\\",\\\"name\\\":\\\"X\\\"}\"}}";
return Stream.of(
@@ -345,6 +360,21 @@ class SesBulkV2IntegrationTest {
"BulkEmailEntries": [null]
}
""".formatted(validDefaultTemplate)),
Arguments.of("DefaultTemplateData as invalid JSON string", """
{
"FromEmailAddress": "bulk@example.com",
"DefaultContent": {
"Template": {"TemplateName": "v2-bulk-welcome", "TemplateData": "{not json"}
},
"BulkEmailEntries": [{"Destination": {"ToAddresses": ["alice@example.com"]}}]
}
""")
);
}
static Stream<Arguments> wrongTypeSendBulkEmailBodies() {
String validDefaultTemplate = "\"DefaultContent\": {\"Template\": {\"TemplateName\": \"v2-bulk-welcome\", \"TemplateData\": \"{\\\"team\\\":\\\"floci\\\",\\\"name\\\":\\\"X\\\"}\"}}";
return Stream.of(
Arguments.of("BulkEmailEntries element is string", """
{
"FromEmailAddress": "bulk@example.com",
@@ -368,15 +398,6 @@ class SesBulkV2IntegrationTest {
"BulkEmailEntries": [{"Destination": {"ToAddresses": ["alice@example.com"]}}]
}
"""),
Arguments.of("DefaultTemplateData as invalid JSON string", """
{
"FromEmailAddress": "bulk@example.com",
"DefaultContent": {
"Template": {"TemplateName": "v2-bulk-welcome", "TemplateData": "{not json"}
},
"BulkEmailEntries": [{"Destination": {"ToAddresses": ["alice@example.com"]}}]
}
"""),
Arguments.of("per-entry ReplacementTemplateData as object", """
{
"FromEmailAddress": "bulk@example.com",
@@ -109,7 +109,7 @@ class SesListManagementOptionsV2IntegrationTest {
@Test
@Order(4)
void listManagementOptionsWithNonStringTopicName_returns400() {
void listManagementOptionsWithNonStringTopicName_returnsSerializationException() {
given().contentType("application/json").header("Authorization", AUTH)
.body("""
{
@@ -120,7 +120,8 @@ class SesListManagementOptionsV2IntegrationTest {
}
""".formatted(FROM, LIST))
.when().post("/v2/email/outbound-emails").then().statusCode(400)
.body("__type", equalTo("BadRequestException"));
.body("__type", equalTo("SerializationException"))
.body("message", equalTo("NUMBER_VALUE can not be converted to a String"));
}
@Test
@@ -1,64 +0,0 @@
package io.github.hectorvent.floci.services.ses;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@QuarkusTest
class SesSendAddressListTypeIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request";
private static final String TO = "success@simulator.amazonses.com";
private static void assertSerializationException(String path, String body) {
given()
.contentType("application/json")
.header("Authorization", AUTH)
.body(body)
.when()
.post(path)
.then()
.statusCode(400)
.body("__type", equalTo("SerializationException"));
}
private static String bulkSend(String replyTo, String entryDestination) {
return """
{
"FromEmailAddress": "sender@example.com",
%s
"DefaultContent": {"Template": {
"TemplateContent": {"Subject": "s", "Text": "b"},
"TemplateData": "{}"}},
"BulkEmailEntries": [{"Destination": %s}]
}
""".formatted(replyTo, entryDestination);
}
@Test
void v2SendEmail_nonArrayReplyTo_returnsSerializationException() {
assertSerializationException("/v2/email/outbound-emails", """
{
"FromEmailAddress": "sender@example.com",
"Destination": {"ToAddresses": ["%s"]},
"ReplyToAddresses": "reply@example.com",
"Content": {"Simple": {"Subject": {"Data": "s"}, "Body": {"Text": {"Data": "b"}}}}
}
""".formatted(TO));
}
@Test
void v2SendBulkEmail_nonArrayReplyTo_returnsSerializationException() {
assertSerializationException("/v2/email/outbound-bulk-emails",
bulkSend("\"ReplyToAddresses\": \"reply@example.com\",", "{\"ToAddresses\": [\"" + TO + "\"]}"));
}
@Test
void v2SendBulkEmail_nonArrayEntryDestinationMember_returnsSerializationException() {
assertSerializationException("/v2/email/outbound-bulk-emails",
bulkSend("", "{\"ToAddresses\": [\"" + TO + "\"], \"CcAddresses\": \"bad-shape\"}"));
}
}
@@ -0,0 +1,209 @@
package io.github.hectorvent.floci.services.ses;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
/**
* A v2 send member of the wrong JSON type fails deserialization on AWS with a
* SerializationException naming the type, ahead of every other check (probe-confirmed). One case
* per member group shows the send endpoints check their body against the SES v2 shapes; the
* messages per JSON type are covered by SesV2RequestShapesTest.
*/
@QuarkusTest
class SesSendMemberTypeIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request";
private static final String TO = "success@simulator.amazonses.com";
private static final String SEND = "/v2/email/outbound-emails";
private static final String BULK = "/v2/email/outbound-bulk-emails";
private static final String VERIFY = "/v2/email/outbound-custom-verification-emails";
private static final String SIMPLE =
"{\"Simple\": {\"Subject\": {\"Data\": \"s\"}, \"Body\": {\"Text\": {\"Data\": \"b\"}}}}";
private static final String INLINE_TEMPLATE =
"{\"Template\": {\"TemplateContent\": {\"Subject\": \"s\", \"Text\": \"b\"}, \"TemplateData\": \"{}\"}}";
private static final String STRUCTURE = "Start of structure or map found where not expected.";
private static final String LIST = "Start of list found where not expected";
private static final String NUMBER = "NUMBER_VALUE can not be converted to a String";
private static final String EXPECTED_LIST = "Expected list or null";
private static void assertError(String path, String body, String type, String message) {
given()
.contentType("application/json")
.header("Authorization", AUTH)
.body(body)
.when()
.post(path)
.then()
.statusCode(400)
.body("__type", equalTo(type))
.body("message", equalTo(message));
}
private static void assertSerializationException(String path, String body, String message) {
assertError(path, body, "SerializationException", message);
}
private static String send(String members, String content) {
return "{" + members + "\"Content\": " + content + "}";
}
private static String bulkSend(String members, String entryDestination) {
return "{" + members + "\"DefaultContent\": " + INLINE_TEMPLATE
+ ", \"BulkEmailEntries\": [{\"Destination\": " + entryDestination + "}]}";
}
private static String rawData() {
return Base64.getEncoder().encodeToString(("From: sender@example.com\r\nTo: " + TO
+ "\r\nSubject: s\r\n\r\nb").getBytes(StandardCharsets.UTF_8));
}
@Test
void v2SendEmail_objectFromEmailAddress_isNotReadAsAbsent() {
assertSerializationException(SEND, send("\"FromEmailAddress\": {},",
"{\"Raw\": {\"Data\": \"" + rawData() + "\"}}"), STRUCTURE);
}
@Test
void v2SendEmail_numericConfigurationSetName_returnsSerializationException() {
assertSerializationException(SEND, send("\"FromEmailAddress\": \"sender@example.com\", "
+ "\"Destination\": {\"ToAddresses\": [\"" + TO + "\"]}, \"ConfigurationSetName\": 123,", SIMPLE),
NUMBER);
}
@Test
void v2SendEmail_numericRawData_namesTheBlobType() {
assertSerializationException(SEND, send("\"FromEmailAddress\": \"sender@example.com\",",
"{\"Raw\": {\"Data\": 123}}"), "NUMBER_VALUE can not be converted to a Blob");
}
@Test
void v2SendEmail_simpleContentTypeErrorPrecedesMissingSender() {
assertSerializationException(SEND, send("\"Destination\": {\"ToAddresses\": [\"" + TO + "\"]},",
"{\"Simple\": {\"Subject\": {\"Data\": 123}, \"Body\": {\"Text\": {\"Data\": \"b\"}}}}"), NUMBER);
}
@Test
void v2SendEmail_stringSubject_returnsExpectedNull() {
assertSerializationException(SEND, send("\"FromEmailAddress\": \"sender@example.com\", "
+ "\"Destination\": {\"ToAddresses\": [\"" + TO + "\"]},",
"{\"Simple\": {\"Subject\": \"s\", \"Body\": {\"Text\": {\"Data\": \"b\"}}}}"), "Expected null");
}
@Test
void v2SendEmail_stringHeaders_returnsExpectedList() {
assertSerializationException(SEND, send("\"FromEmailAddress\": \"sender@example.com\", "
+ "\"Destination\": {\"ToAddresses\": [\"" + TO + "\"]},",
"{\"Simple\": {\"Subject\": {\"Data\": \"s\"}, \"Body\": {\"Text\": {\"Data\": \"b\"}}, "
+ "\"Headers\": \"X-A: b\"}}"), EXPECTED_LIST);
}
@Test
void v2SendEmail_templateNameTypeErrorPrecedesMissingSender() {
assertSerializationException(SEND, send("\"Destination\": {\"ToAddresses\": [\"" + TO + "\"]},",
"{\"Template\": {\"TemplateName\": 123, \"TemplateData\": \"{}\"}}"), NUMBER);
}
@Test
void v2SendEmail_stringDestination_returnsExpectedNull() {
assertSerializationException(SEND, send("\"FromEmailAddress\": \"sender@example.com\", "
+ "\"Destination\": \"" + TO + "\",", SIMPLE), "Expected null");
}
@Test
void v2SendEmail_arrayDestination_returnsStartOfList() {
assertSerializationException(SEND, send("\"FromEmailAddress\": \"sender@example.com\", "
+ "\"Destination\": [\"" + TO + "\"],", SIMPLE), LIST);
}
@Test
void v2SendEmail_nonArrayReplyTo_returnsExpectedList() {
assertSerializationException(SEND, send("\"FromEmailAddress\": \"sender@example.com\", "
+ "\"Destination\": {\"ToAddresses\": [\"" + TO + "\"]}, "
+ "\"ReplyToAddresses\": \"reply@example.com\",", SIMPLE), EXPECTED_LIST);
}
@Test
void v2SendEmail_nullReplyToElement_isAnInvalidAddress() {
assertError(SEND, send("\"FromEmailAddress\": \"sender@example.com\", "
+ "\"Destination\": {\"ToAddresses\": [\"" + TO + "\"]}, \"ReplyToAddresses\": [null],", SIMPLE),
"BadRequestException", "Invalid email address null.");
}
@Test
void v2SendEmail_nullAddressElementIsReportedAfterContentTypeErrors() {
assertSerializationException(SEND, send("\"FromEmailAddress\": \"sender@example.com\", "
+ "\"Destination\": {\"ToAddresses\": [\"" + TO + "\"]}, \"ReplyToAddresses\": [null],",
"{\"Simple\": {\"Subject\": {\"Data\": 123}, \"Body\": {\"Text\": {\"Data\": \"b\"}}}}"), NUMBER);
}
@Test
void v2SendEmail_contentTypeErrorPrecedesEmailTagValidation() {
assertSerializationException(SEND, send("\"FromEmailAddress\": \"sender@example.com\", "
+ "\"EmailTags\": [{\"Name\": \"\", \"Value\": \"v\"}],",
"{\"Raw\": {\"Data\": 123}}"), "NUMBER_VALUE can not be converted to a Blob");
}
@Test
void v2SendBulkEmail_replyToTypeErrorPrecedesMissingSender() {
assertSerializationException(BULK, bulkSend("\"ReplyToAddresses\": \"reply@example.com\",",
"{\"ToAddresses\": [\"" + TO + "\"]}"), EXPECTED_LIST);
}
@Test
void v2SendBulkEmail_entryDestinationTypeErrorPrecedesMalformedSender() {
assertSerializationException(BULK, bulkSend("\"FromEmailAddress\": \"sender@\",",
"{\"ToAddresses\": [\"" + TO + "\"], \"CcAddresses\": \"bad-shape\"}"), EXPECTED_LIST);
}
@Test
void v2SendBulkEmail_arrayEntryDestination_returnsStartOfList() {
assertSerializationException(BULK, bulkSend("\"FromEmailAddress\": \"sender@example.com\",",
"[\"" + TO + "\"]"), LIST);
}
@Test
void v2SendBulkEmail_numericFromEmailAddress_returnsSerializationException() {
assertSerializationException(BULK, bulkSend("\"FromEmailAddress\": 123,",
"{\"ToAddresses\": [\"" + TO + "\"]}"), NUMBER);
}
@Test
void v2SendBulkEmail_nullReplyToElementIsReportedAfterEntryTypeErrors() {
assertSerializationException(BULK, bulkSend("\"FromEmailAddress\": \"sender@example.com\", "
+ "\"ReplyToAddresses\": [null],", "{\"ToAddresses\": [1]}"), NUMBER);
}
@Test
void v2SendBulkEmail_entryReplacementTypeErrorPrecedesMissingStoredTemplate() {
assertSerializationException(BULK, """
{
"FromEmailAddress": "sender@example.com",
"DefaultContent": {"Template": {"TemplateName": "no-such-template", "TemplateData": "{}"}},
"BulkEmailEntries": [{"Destination": {"ToAddresses": ["%s"]}, "ReplacementTags": "bad"}]
}
""".formatted(TO), EXPECTED_LIST);
}
@Test
void v2SendBulkEmail_entryTypeErrorPrecedesMissingStoredTemplate() {
assertSerializationException(BULK, """
{
"FromEmailAddress": "sender@example.com",
"DefaultContent": {"Template": {"TemplateName": "no-such-template", "TemplateData": "{}"}},
"BulkEmailEntries": [{"Destination": {"ToAddresses": [1]}}]
}
""", NUMBER);
}
@Test
void v2SendCustomVerificationEmail_numericEmailAddress_returnsSerializationException() {
assertSerializationException(VERIFY, "{\"EmailAddress\": 123, \"TemplateName\": \"t\"}", NUMBER);
}
}
@@ -0,0 +1,133 @@
package io.github.hectorvent.floci.services.ses;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
/**
* A null address element passes deserialization on AWS and fails later (probe-confirmed): on
* SendEmail after the content and sender checks and before the tenant lookup, on SendBulkEmail as
* the status of the entries it affects.
*/
@QuarkusTest
class SesSendNullAddressIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request";
private static final String SENDER = "sender@example.com";
private static final String TO = "success@simulator.amazonses.com";
private static final String SIMPLE =
"{\"Simple\": {\"Subject\": {\"Data\": \"s\"}, \"Body\": {\"Text\": {\"Data\": \"b\"}}}}";
private static final String INLINE_TEMPLATE =
"{\"Template\": {\"TemplateContent\": {\"Subject\": \"s\", \"Text\": \"b\"}, \"TemplateData\": \"{}\"}}";
private static final String NULL_ADDRESS = "Invalid email address null.";
private static final String EMPTY_DESTINATION = "Destination cannot be empty";
private static ValidatableResponse post(String path, String body) {
return given()
.contentType("application/json")
.header("Authorization", AUTH)
.body(body)
.when()
.post(path)
.then();
}
private static ValidatableResponse send(String body) {
return post("/v2/email/outbound-emails", body);
}
private static ValidatableResponse bulk(String members, String entries) {
return post("/v2/email/outbound-bulk-emails", "{\"FromEmailAddress\": \"" + SENDER + "\", " + members
+ "\"DefaultContent\": " + INLINE_TEMPLATE + ", \"BulkEmailEntries\": [" + entries + "]}");
}
private static String entry(String destination) {
return "{\"Destination\": " + destination + "}";
}
@Test
void sendEmail_nullToAddress_isAnInvalidAddress() {
send("{\"FromEmailAddress\": \"" + SENDER + "\", \"Destination\": {\"ToAddresses\": [null]}, "
+ "\"Content\": " + SIMPLE + "}")
.statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo(NULL_ADDRESS));
}
@Test
void sendEmail_missingContentPrecedesNullAddress() {
send("{\"FromEmailAddress\": \"" + SENDER + "\", \"Destination\": {\"ToAddresses\": [\"" + TO + "\"]}, "
+ "\"ReplyToAddresses\": [null]}")
.statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("Content must contain Raw, Simple, or Template."));
}
@Test
void sendEmail_missingSenderPrecedesNullAddress() {
send("{\"Destination\": {\"ToAddresses\": [\"" + TO + "\"]}, \"ReplyToAddresses\": [null], "
+ "\"Content\": " + SIMPLE + "}")
.statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", nullValue());
}
@Test
void sendEmail_nullAddressPrecedesTenantLookup() {
send("{\"FromEmailAddress\": \"" + SENDER + "\", \"Destination\": {\"ToAddresses\": [\"" + TO + "\"]}, "
+ "\"ReplyToAddresses\": [null], \"TenantName\": \"no-such-tenant\", \"Content\": " + SIMPLE + "}")
.statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo(NULL_ADDRESS));
}
@Test
void sendBulkEmail_onlyNullRecipientsInTheRequest_answerEmptyDestination() {
bulk("", entry("{\"ToAddresses\": [null]}") + ", " + entry("{\"ToAddresses\": [null]}"))
.statusCode(200)
.body("BulkEmailEntryResults[0].Status", equalTo("INVALID_PARAMETER"))
.body("BulkEmailEntryResults[0].Error", equalTo(EMPTY_DESTINATION))
.body("BulkEmailEntryResults[1].Status", equalTo("INVALID_PARAMETER"))
.body("BulkEmailEntryResults[1].Error", equalTo(EMPTY_DESTINATION));
}
@Test
void sendBulkEmail_nullRecipientBesideAnotherEntrysRecipient_isAnInvalidAddress() {
bulk("", entry("{\"ToAddresses\": [null]}") + ", " + entry("{\"ToAddresses\": [\"" + TO + "\"]}"))
.statusCode(200)
.body("BulkEmailEntryResults[0].Status", equalTo("INVALID_PARAMETER"))
.body("BulkEmailEntryResults[0].Error", equalTo(NULL_ADDRESS));
}
@Test
void sendBulkEmail_nullRecipientBesideARecipient_isAnInvalidAddress() {
bulk("", entry("{\"ToAddresses\": [null, \"" + TO + "\"]}"))
.statusCode(200)
.body("BulkEmailEntryResults[0].Status", equalTo("INVALID_PARAMETER"))
.body("BulkEmailEntryResults[0].Error", equalTo(NULL_ADDRESS));
}
@Test
void sendBulkEmail_nullCcAddress_isAnInvalidAddress() {
bulk("", entry("{\"ToAddresses\": [\"" + TO + "\"], \"CcAddresses\": [null]}"))
.statusCode(200)
.body("BulkEmailEntryResults[0].Status", equalTo("INVALID_PARAMETER"))
.body("BulkEmailEntryResults[0].Error", equalTo(NULL_ADDRESS));
}
@Test
void sendBulkEmail_nullReplyToAddress_failsEveryEntry() {
bulk("\"ReplyToAddresses\": [null], ", entry("{\"ToAddresses\": [\"" + TO + "\"]}") + ", "
+ entry("{\"ToAddresses\": [\"" + TO + "\"]}"))
.statusCode(200)
.body("BulkEmailEntryResults[0].Status", equalTo("INVALID_PARAMETER"))
.body("BulkEmailEntryResults[0].Error", equalTo(NULL_ADDRESS))
.body("BulkEmailEntryResults[1].Status", equalTo("INVALID_PARAMETER"))
.body("BulkEmailEntryResults[1].Error", equalTo(NULL_ADDRESS));
}
}
@@ -684,11 +684,40 @@ class SesTemplateV2IntegrationTest {
.body("__type", equalTo("BadRequestException"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("wrongTypeSendEmailBodies")
@Order(51)
void sendEmail_wrongMemberType_returnsSerializationException(String label, String body) {
given()
.contentType("application/json")
.header("Authorization", AUTH_HEADER)
.body(body)
.when()
.post("/v2/email/outbound-emails")
.then()
.statusCode(400)
.body("__type", equalTo("SerializationException"));
}
static Stream<Arguments> malformedSendEmailBodies() {
return Stream.of(
Arguments.of("body is array", "[1,2,3]"),
Arguments.of("body is JSON null literal", "null"),
Arguments.of("body is JSON string", "\"hello\""),
Arguments.of("TemplateData as invalid JSON string", """
{
"FromEmailAddress": "sender@example.com",
"Destination": {"ToAddresses": ["recipient@example.com"]},
"Content": {
"Template": {"TemplateName": "any", "TemplateData": "{not json"}
}
}
""")
);
}
static Stream<Arguments> wrongTypeSendEmailBodies() {
return Stream.of(
Arguments.of("Destination as string", """
{
"FromEmailAddress": "sender@example.com",
@@ -713,15 +742,6 @@ class SesTemplateV2IntegrationTest {
"Template": {"TemplateName": "any", "TemplateData": [1,2,3]}
}
}
"""),
Arguments.of("TemplateData as invalid JSON string", """
{
"FromEmailAddress": "sender@example.com",
"Destination": {"ToAddresses": ["recipient@example.com"]},
"Content": {
"Template": {"TemplateName": "any", "TemplateData": "{not json"}
}
}
""")
);
}
@@ -0,0 +1,102 @@
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 org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class SesV2RequestShapesTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String STRUCTURE = "Start of structure or map found where not expected.";
private static final String LIST = "Start of list found where not expected";
@Test
void stringMemberNamesTheJsonTokenItGot() {
assertRejected("SendEmail", "{\"FromEmailAddress\":123}", "NUMBER_VALUE can not be converted to a String");
assertRejected("SendEmail", "{\"FromEmailAddress\":true}", "TRUE_VALUE can not be converted to a String");
assertRejected("SendEmail", "{\"FromEmailAddress\":false}", "FALSE_VALUE can not be converted to a String");
assertRejected("SendEmail", "{\"FromEmailAddress\":{}}", STRUCTURE);
assertRejected("SendEmail", "{\"FromEmailAddress\":[]}", LIST);
}
@Test
void blobMemberNamesTheBlobType() {
assertRejected("SendEmail", "{\"Content\":{\"Raw\":{\"Data\":123}}}", "NUMBER_VALUE can not be converted to a Blob");
assertRejected("SendEmail", "{\"Content\":{\"Raw\":{\"Data\":true}}}", "TRUE_VALUE can not be converted to a Blob");
assertRejected("SendEmail", "{\"Content\":{\"Raw\":{\"Data\":{}}}}", STRUCTURE);
}
@Test
void structureMemberTakesOnlyAnObject() {
assertRejected("SendEmail", "{\"Destination\":\"to@example.com\"}", "Expected null");
assertRejected("SendEmail", "{\"Destination\":123}", "Expected null");
assertRejected("SendEmail", "{\"Destination\":[]}", LIST);
assertRejected("SendEmail", "{\"Content\":{\"Simple\":{\"Subject\":\"s\"}}}", "Expected null");
}
@Test
void listMemberTakesOnlyAnArray() {
assertRejected("SendEmail", "{\"ReplyToAddresses\":\"r@example.com\"}", "Expected list or null");
assertRejected("SendEmail", "{\"ReplyToAddresses\":123}", "Expected list or null");
assertRejected("SendEmail", "{\"ReplyToAddresses\":{}}", STRUCTURE);
assertRejected("SendEmail", "{\"ReplyToAddresses\":[123]}", "NUMBER_VALUE can not be converted to a String");
assertRejected("SendBulkEmail", "{\"BulkEmailEntries\":[{\"Destination\":[]}]}", LIST);
}
@Test
void mapMemberReadsLikeAStructure() {
assertAccepted("ListTenantResources", "{\"Filter\":{\"RESOURCE_TYPE\":\"x\"}}");
assertRejected("ListTenantResources", "{\"Filter\":[]}", LIST);
assertRejected("ListTenantResources", "{\"Filter\":\"x\"}", "Expected null");
assertRejected("ListTenantResources", "{\"Filter\":{\"RESOURCE_TYPE\":1}}",
"NUMBER_VALUE can not be converted to a String");
}
@Test
void firstBadMemberInBodyOrderIsReported() {
assertRejected("SendEmail", "{\"Destination\":[],\"FromEmailAddress\":123}", LIST);
assertRejected("SendEmail", "{\"FromEmailAddress\":123,\"Destination\":[]}",
"NUMBER_VALUE can not be converted to a String");
}
@Test
void nullsUnknownMembersAndUnprobedTypesAreLeftToTheOperation() {
assertAccepted("SendEmail", "{\"FromEmailAddress\":null,\"Destination\":null,\"Unknown\":5}");
assertAccepted("SendEmail", "{\"ReplyToAddresses\":[null]}");
assertAccepted("PutAccountSendingAttributes", "{\"SendingEnabled\":\"maybe\"}");
assertAccepted("PutConfigurationSetDeliveryOptions", "{\"MaxDeliverySeconds\":\"x\"}");
}
@Test
void unknownOperationIsAServerError() {
AwsException error = assertThrows(AwsException.class,
() -> SesV2RequestShapes.check("NoSuchOperation", json("{}")));
assertEquals("InternalFailure", error.getErrorCode());
assertEquals(500, error.getHttpStatus());
}
@Test
void bodyShapesLeaveOutUriAndQueryMembers() {
assertAccepted("GetEmailIdentity", "{\"EmailIdentity\":123}");
}
private static void assertRejected(String operation, String body, String message) {
AwsException error = assertThrows(AwsException.class, () -> SesV2RequestShapes.check(operation, json(body)));
assertEquals("SerializationException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertEquals(message, error.getMessage());
}
private static void assertAccepted(String operation, String body) {
assertDoesNotThrow(() -> SesV2RequestShapes.check(operation, json(body)));
}
private static JsonNode json(String body) throws Exception {
return MAPPER.readTree(body);
}
}
@@ -0,0 +1,23 @@
{
"_source": {
"generator": "RequestShapeModelTest"
},
"operations": {
"Send": "SendRequest"
},
"shapes": {
"SendRequest": {
"type": "structure",
"members": {
"To": "Addresses"
}
},
"Addresses": {
"type": "list",
"member": "Address"
},
"Address": {
"type": "string"
}
}
}
+2 -2
View File
@@ -31,8 +31,8 @@ OUTPUT = REPO_ROOT / "src/main/resources/aws/dynamodb-request-shapes.json"
MODEL = Path("dynamodb/2012-08-10/service-2.json")
def load_model(data: Path) -> dict:
plain = data / MODEL
def load_model(data: Path, model: Path = MODEL) -> dict:
plain = data / model
if plain.exists():
return json.loads(plain.read_text(encoding="utf-8"))
compressed = plain.with_name(plain.name + ".gz")
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""Regenerate src/main/resources/aws/sesv2-request-shapes.json from botocore's SES v2 model.
SES v2 rejects a request body member of the wrong JSON type with a SerializationException before
it validates anything. The Java side (`SesV2RequestShapes`) needs each operation's body shapes to
do the same, so this script keeps only what that check reads: the input shape of every
operation, reduced to the members carried in the JSON body, and for every shape reachable from
one, its type and the shapes of its members, list elements or map values.
Members bound to the URI, the query string or a header are left out: they never reach the body,
and an operation whose binding moved (ListEmailIdentities went from a GET with a query string
to a POST with a body) keeps its old route served by hand.
The model is botocore's `sesv2/2019-09-27/service-2.json` (Apache-2.0,
https://github.com/boto/botocore). It is located, in order, at `--botocore-data`, the
`local/aws/botocore` checkout, then the installed `botocore` package, which `requirements.txt`
pins so CI regenerates the same bytes.
Run from anywhere in the repo:
python3 tools/aws/regen_sesv2_shapes.py # rewrite the vendored file in place
python3 tools/aws/regen_sesv2_shapes.py --check # exit 1 when the vendored file is stale
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
from regen_dynamodb_shapes import load_model, render
from regen_partitions import resolve_botocore_data, strip_source
REPO_ROOT = Path(__file__).resolve().parents[2]
OUTPUT = REPO_ROOT / "src/main/resources/aws/sesv2-request-shapes.json"
MODEL = Path("sesv2/2019-09-27/service-2.json")
def build(model: dict, provenance: str) -> dict:
shapes = model["shapes"]
kept: dict[str, dict] = {}
def keep(name: str, body_only: bool = False) -> None:
if name in kept:
return
shape = shapes[name]
kind = shape["type"]
entry: dict = {"type": kind}
kept[name] = entry
if kind == "structure":
members = {member: spec for member, spec in shape.get("members", {}).items()
if not (body_only and "location" in spec)}
entry["members"] = {member: spec["shape"] for member, spec in members.items()}
for spec in members.values():
keep(spec["shape"])
elif kind == "list":
entry["member"] = shape["member"]["shape"]
keep(shape["member"]["shape"])
elif kind == "map":
entry["value"] = shape["value"]["shape"]
keep(shape["value"]["shape"])
operations = {}
for name, operation in sorted(model["operations"].items()):
if "input" in operation:
operations[name] = operation["input"]["shape"]
keep(operation["input"]["shape"], body_only=True)
return {
"_source": {
"generator": "tools/aws/regen_sesv2_shapes.py",
"botocore": provenance,
},
"operations": operations,
"shapes": dict(sorted(kept.items())),
}
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--check", action="store_true", help="exit 1 when the vendored file differs from a fresh generation")
parser.add_argument("--botocore-data", type=Path, help="botocore data directory")
parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS)
args = parser.parse_args(argv)
data, provenance = resolve_botocore_data(args.botocore_data)
fresh = render(build(load_model(data, MODEL), provenance))
if args.check:
current = args.output.read_text(encoding="utf-8") if args.output.exists() else ""
if strip_source(current) != strip_source(fresh):
print(f"{args.output} is stale (generated from {provenance}).", file=sys.stderr)
return 1
return 0
args.output.write_text(fresh, encoding="utf-8")
print(f"wrote {args.output.relative_to(REPO_ROOT)} from {provenance}")
return 0
if __name__ == "__main__":
sys.exit(main())
+76
View File
@@ -0,0 +1,76 @@
"""Tests for regen_sesv2_shapes.
Run with: pytest tools/aws -q (or: make aws-data-test)
"""
from __future__ import annotations
import regen_sesv2_shapes as r
MODEL = {
"operations": {
"SendEmail": {"input": {"shape": "SendEmailRequest"}, "output": {"shape": "SendEmailResponse"}},
"GetEmailIdentity": {"input": {"shape": "GetEmailIdentityRequest"}},
"NoInput": {},
},
"shapes": {
"SendEmailRequest": {"type": "structure", "members": {
"FromEmailAddress": {"shape": "EmailAddress"},
"ReplyToAddresses": {"shape": "EmailAddressList"},
"Content": {"shape": "EmailContent"},
}},
"SendEmailResponse": {"type": "structure", "members": {"MessageId": {"shape": "OutboundMessageId"}}},
"GetEmailIdentityRequest": {"type": "structure", "members": {
"EmailIdentity": {"shape": "Identity", "location": "uri", "locationName": "EmailIdentity"},
"NextToken": {"shape": "NextToken", "location": "querystring", "locationName": "NextToken"},
}},
"EmailAddress": {"type": "string"},
"EmailAddressList": {"type": "list", "member": {"shape": "EmailAddress"}},
"EmailContent": {"type": "structure", "members": {"Raw": {"shape": "RawMessage"}}},
"RawMessage": {"type": "structure", "members": {"Data": {"shape": "RawMessageData"}}},
"RawMessageData": {"type": "blob"},
"OutboundMessageId": {"type": "string"},
"Identity": {"type": "string", "min": 1},
"NextToken": {"type": "string"},
},
}
def test_keeps_only_body_members_of_input_shapes():
doc = r.build(MODEL, "botocore test")
assert doc["_source"] == {"generator": "tools/aws/regen_sesv2_shapes.py", "botocore": "botocore test"}
assert doc["operations"] == {"GetEmailIdentity": "GetEmailIdentityRequest", "SendEmail": "SendEmailRequest"}
assert "SendEmailResponse" not in doc["shapes"]
assert "OutboundMessageId" not in doc["shapes"]
assert doc["shapes"]["SendEmailRequest"] == {"type": "structure", "members": {
"FromEmailAddress": "EmailAddress", "ReplyToAddresses": "EmailAddressList", "Content": "EmailContent"}}
assert doc["shapes"]["EmailAddressList"] == {"type": "list", "member": "EmailAddress"}
assert doc["shapes"]["RawMessageData"] == {"type": "blob"}
def test_drops_uri_and_query_members():
doc = r.build(MODEL, "botocore test")
assert doc["shapes"]["GetEmailIdentityRequest"] == {"type": "structure", "members": {}}
assert "Identity" not in doc["shapes"]
assert "NextToken" not in doc["shapes"]
def test_check_ignores_provenance(tmp_path, monkeypatch):
output = tmp_path / "shapes.json"
output.write_text(r.render(r.build(MODEL, "botocore 0.0.1 (local/aws/botocore)")), encoding="utf-8")
monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "--botocore-data /elsewhere"))
monkeypatch.setattr(r, "load_model", lambda data, model: MODEL)
assert r.main(["--check", "--output", str(output)]) == 0
def test_check_reports_changed_shapes(tmp_path, monkeypatch):
output = tmp_path / "shapes.json"
changed = {**MODEL, "shapes": {**MODEL["shapes"], "EmailAddress": {"type": "integer"}}}
output.write_text(r.render(r.build(changed, "botocore test")), encoding="utf-8")
monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "botocore test"))
monkeypatch.setattr(r, "load_model", lambda data, model: MODEL)
assert r.main(["--check", "--output", str(output)]) == 1