feat(cloudformation): provision SES event destinations (#8620)

* feat(cloudformation): provision SES event destinations
* fix(cloudformation): validate SES event destination replacements
* fix(cloudformation): apply SES event destination review feedback
* test(cloudformation): use shared stack waits for SES event destinations
This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-11-16 17:08:48 -04:00
1 parent aef8416c4b
commit 5f77b841a2
22 files changed
+1264 -104

No files matched your search

@@ -8,6 +8,7 @@ import org.jboss.logging.Logger;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -19,21 +20,24 @@ public final class CfnCreateOnlyProperties {
private static final Logger LOG = Logger.getLogger(CfnCreateOnlyProperties.class);
private static final String RESOURCE_NAME = "cloudformation/create-only-properties.json";
private static final Map<String, Set<String>> PROPERTIES = load();
private static final String CONDITIONAL_RESOURCE_NAME =
"cloudformation/conditional-create-only-properties.json";
private static final Map<String, Set<String>> PROPERTIES = load(RESOURCE_NAME);
private static final Map<String, Set<String>> CONDITIONAL_PROPERTIES = load(CONDITIONAL_RESOURCE_NAME);
private CfnCreateOnlyProperties() {
}
private static Map<String, Set<String>> load() {
try (InputStream in = CfnCreateOnlyProperties.class.getClassLoader().getResourceAsStream(RESOURCE_NAME)) {
private static Map<String, Set<String>> load(String resourceName) {
try (InputStream in = CfnCreateOnlyProperties.class.getClassLoader().getResourceAsStream(resourceName)) {
if (in == null) {
LOG.warnv("Resource {0} not found on classpath", RESOURCE_NAME);
LOG.warnv("Resource {0} not found on classpath", resourceName);
return Collections.emptyMap();
}
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(in, new TypeReference<Map<String, Set<String>>>() {});
} catch (Exception e) {
LOG.warnv(e, "Failed to load {0}", RESOURCE_NAME);
LOG.warnv(e, "Failed to load {0}", resourceName);
return Collections.emptyMap();
}
}
@@ -68,6 +72,18 @@ public final class CfnCreateOnlyProperties {
return PROPERTIES.getOrDefault(resourceType, Collections.emptySet());
}
/** Schema pointers that require replacement, including conditionally create-only paths. */
static Set<String> replacementPointers(String resourceType) {
Set<String> schemaPointers = getCreateOnlyProperties(resourceType);
Set<String> conditionalPointers = CONDITIONAL_PROPERTIES.get(resourceType);
if (conditionalPointers == null || conditionalPointers.isEmpty()) {
return schemaPointers;
}
Set<String> pointers = new HashSet<>(schemaPointers);
pointers.addAll(conditionalPointers);
return pointers;
}
/** True when the registry table has an entry for the type, so its pointers are authoritative. */
public static boolean hasSchema(String resourceType) {
return PROPERTIES.containsKey(resourceType);
@@ -80,7 +96,7 @@ public final class CfnCreateOnlyProperties {
* element's subtree.
*/
public static boolean createOnlyValueChanged(String resourceType, JsonNode oldProps, JsonNode newProps) {
for (String pointer : getCreateOnlyProperties(resourceType)) {
for (String pointer : replacementPointers(resourceType)) {
if (createOnlyPointerChanged(pointer, oldProps, newProps)) {
return true;
}
@@ -104,7 +120,7 @@ public final class CfnCreateOnlyProperties {
/** The subtrees of the new properties that sit under a create-only pointer of the type. */
public static List<JsonNode> createOnlySubtrees(String resourceType, JsonNode props) {
List<JsonNode> out = new ArrayList<>();
for (String pointer : getCreateOnlyProperties(resourceType)) {
for (String pointer : replacementPointers(resourceType)) {
collect(props, pointer.split("/"), 0, out);
}
return out;
@@ -1591,7 +1591,7 @@ public class CloudFormationService implements ResourceProvider {
}
JsonNode digestedBefore = digested(before);
JsonNode digestedAfter = digested(after);
for (String pointer : CfnCreateOnlyProperties.getCreateOnlyProperties(resourceType)) {
for (String pointer : CfnCreateOnlyProperties.replacementPointers(resourceType)) {
boolean changed = noEvidence(pointer, before)
? writtenPointerChanged(pointer, oldProps, newProps)
: CfnCreateOnlyProperties.createOnlyPointerChanged(pointer, digestedBefore, digestedAfter);
@@ -0,0 +1,76 @@
package io.floci.aws.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.services.cloudformation.model.StackResource;
import java.util.function.Consumer;
/** Cleanup records shared by resources whose physical name is only part of their deletion address. */
final class CfnLifecycleRecords {
private static final ObjectMapper MAPPER = new ObjectMapper();
private CfnLifecycleRecords() {
}
static ObjectNode read(StackResource resource, String attribute, String invalid, String wrongShape) {
String raw = resource.getAttributes().get(attribute);
if (raw == null) {
return null;
}
try {
if (MAPPER.readTree(raw) instanceof ObjectNode object) {
return object;
}
throw new IllegalStateException(wrongShape);
} catch (JsonProcessingException failure) {
throw new IllegalStateException(invalid, failure);
}
}
static void setCleanup(StackResource resource, String attribute, ObjectNode address, boolean retainable) {
resource.getAttributes().put(attribute,
address.put("retainable", retainable).put("attempts", 0).toString());
}
static boolean retained(StackResource resource, JsonNode pending) {
return pending.path("retainable").asBoolean() && "Retain".equals(resource.getUpdateReplacePolicy());
}
static void deletePending(StackResource resource, String attribute, ObjectNode pending,
boolean honorRetain, Consumer<ObjectNode> delete) {
if (pending == null) {
return;
}
if (!honorRetain || !retained(resource, pending)) {
delete.accept(pending);
}
resource.getAttributes().remove(attribute);
}
static String cleanupPhysicalId(StackResource resource, ObjectNode pending) {
return pending == null || retained(resource, pending) ? null : pending.path("name").asText();
}
static UpdateCleanupResult completePending(StackResource resource, String cleanupAttribute,
String updateAttribute, ObjectNode pending,
boolean honorRetain, Consumer<ObjectNode> delete) {
if (pending == null) {
return resource.getAttributes().containsKey(updateAttribute)
? new UpdateCleanupResult(true, true, null, 0, null)
: UpdateCleanupResult.notApplicable();
}
String name = pending.path("name").asText();
try {
deletePending(resource, cleanupAttribute, pending, honorRetain, delete);
return new UpdateCleanupResult(true, true, name, 0, null);
} catch (RuntimeException failure) {
int attempts = pending.path("attempts").asInt() + 1;
pending.put("attempts", attempts);
resource.getAttributes().put(cleanupAttribute, pending.toString());
return new UpdateCleanupResult(true, false, name, attempts, failure.getMessage());
}
}
}
@@ -82,6 +82,35 @@ final class CfnPropertyTypes {
return shape;
}
/** Reject unmodeled members for a provisioner that passes the whole schema-shaped object to a service. */
static void rejectUnknownMembers(String resourceType, JsonNode properties) {
String shape = Holder.MODEL.operations().get(resourceType);
if (shape == null) {
throw notVendored(resourceType);
}
rejectUnknownMembers(properties, shape);
}
private static void rejectUnknownMembers(JsonNode value, String shapeName) {
if (value == null || value.isNull()) {
return;
}
Shape shape = Holder.MODEL.shapes().get(shapeName);
if ("structure".equals(shape.type()) && value.isObject()) {
value.properties().forEach(member -> {
String nested = shape.members().get(member.getKey());
if (nested == null) {
throw new AwsException("ValidationError", "Unknown property: " + member.getKey(), 400);
}
rejectUnknownMembers(member.getValue(), nested);
});
} else if ("list".equals(shape.type()) && value.isArray()) {
value.forEach(element -> rejectUnknownMembers(element, shape.element()));
} else if ("map".equals(shape.type()) && value.isObject()) {
value.forEach(element -> rejectUnknownMembers(element, shape.element()));
}
}
private static IllegalStateException notVendored(String what) {
return new IllegalStateException(what + " is not in " + RESOURCE_NAME
+ "; add the type to tools/aws/regen_cfn_property_types.py");
@@ -1,6 +1,5 @@
package io.floci.aws.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
@@ -139,8 +138,7 @@ public class LogsLogStreamCfnProvisioner implements CfnResourceProvisioner {
}
private static void setCleanup(StackResource resource, Identity identity, String region, boolean retainable) {
ObjectNode cleanup = address(identity, region).put("retainable", retainable).put("attempts", 0);
resource.getAttributes().put(CLEANUP_ATTR, cleanup.toString());
CfnLifecycleRecords.setCleanup(resource, CLEANUP_ATTR, address(identity, region), retainable);
}
@Override
@@ -161,10 +159,8 @@ public class LogsLogStreamCfnProvisioner implements CfnResourceProvisioner {
private void deletePending(StackResource resource) {
ObjectNode cleanup = read(resource, CLEANUP_ATTR);
if (cleanup != null) {
delete(identity(cleanup), cleanup.path("region").asText());
resource.getAttributes().remove(CLEANUP_ATTR);
}
CfnLifecycleRecords.deletePending(resource, CLEANUP_ATTR, cleanup, false,
record -> delete(identity(record), record.path("region").asText()));
}
@Override
@@ -195,35 +191,14 @@ public class LogsLogStreamCfnProvisioner implements CfnResourceProvisioner {
@Override
public String updateCleanupPhysicalId(StackResource resource) {
ObjectNode cleanup = read(resource, CLEANUP_ATTR);
return cleanup == null || retained(resource, cleanup) ? null : cleanup.path("name").asText();
return CfnLifecycleRecords.cleanupPhysicalId(resource, cleanup);
}
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
ObjectNode cleanup = read(resource, CLEANUP_ATTR);
if (cleanup == null) {
return resource.getAttributes().containsKey(UPDATE_ATTR)
? new UpdateCleanupResult(true, true, null, 0, null)
: UpdateCleanupResult.notApplicable();
}
String name = cleanup.path("name").asText();
if (retained(resource, cleanup)) {
resource.getAttributes().remove(CLEANUP_ATTR);
return new UpdateCleanupResult(true, true, name, 0, null);
}
try {
deletePending(resource);
return new UpdateCleanupResult(true, true, name, 0, null);
} catch (RuntimeException failure) {
int attempts = cleanup.path("attempts").asInt() + 1;
cleanup.put("attempts", attempts);
resource.getAttributes().put(CLEANUP_ATTR, cleanup.toString());
return new UpdateCleanupResult(true, false, name, attempts, failure.getMessage());
}
}
private static boolean retained(StackResource resource, JsonNode cleanup) {
return cleanup.path("retainable").asBoolean() && "Retain".equals(resource.getUpdateReplacePolicy());
return CfnLifecycleRecords.completePending(resource, CLEANUP_ATTR, UPDATE_ATTR, cleanup, true,
record -> delete(identity(record), record.path("region").asText()));
}
@Override
@@ -233,18 +208,7 @@ public class LogsLogStreamCfnProvisioner implements CfnResourceProvisioner {
}
private static ObjectNode read(StackResource resource, String attribute) {
String raw = resource.getAttributes().get(attribute);
if (raw == null) {
return null;
}
try {
JsonNode record = MAPPER.readTree(raw);
if (record.isObject()) {
return (ObjectNode) record;
}
} catch (JsonProcessingException e) {
throw new IllegalStateException("Invalid log stream lifecycle record for " + resource.getLogicalId(), e);
}
throw new IllegalStateException("Invalid log stream lifecycle record for " + resource.getLogicalId());
String error = "Invalid log stream lifecycle record for " + resource.getLogicalId();
return CfnLifecycleRecords.read(resource, attribute, error, error);
}
}
@@ -0,0 +1,349 @@
package io.floci.aws.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.ses.SesConfigurationSetService;
import io.floci.aws.services.ses.model.EventDestination;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.Set;
@ApplicationScoped
public class SesEventDestinationCfnProvisioner implements CfnResourceProvisioner {
private static final String TYPE = "AWS::SES::ConfigurationSetEventDestination";
private static final String SET_ATTR = "__FlociSesEventDestinationConfigurationSet";
private static final String NAME_MODE_ATTR = "__FlociSesEventDestinationNameMode";
private static final String UPDATE_ATTR = "__FlociSesEventDestinationUpdate";
private static final String CLEANUP_ATTR = "__FlociSesEventDestinationCleanup";
private static final ObjectMapper MAPPER = new ObjectMapper();
private final SesConfigurationSetService configurationSets;
@Inject
public SesEventDestinationCfnProvisioner(SesConfigurationSetService configurationSets) {
this.configurationSets = configurationSets;
}
@Override
public Set<String> resourceTypes() {
return Set.of(TYPE);
}
@Override
public void provision(StackResource resource, JsonNode properties, ProvisionContext ctx) {
if (resource.getAttributes().containsKey(UPDATE_ATTR)) {
rollbackUpdate(resource);
ctx = ctx.withPriorPhysicalId(resource.getPhysicalId());
}
JsonNode resolved = ctx.engine().resolveNodeOmittingNoValue(properties);
if (resolved == null || !resolved.isObject()) {
throw invalid("Properties must be an object.");
}
CfnPropertyTypes.rejectUnknownMembers(TYPE, resolved);
if (resolved.has("Id")) {
throw invalid("Unknown property: Id");
}
rejectNullDestinationBlocks(resolved.path("EventDestination"));
JsonNode props = new CfnPropertyTypes.HandlerReader(ctx.engine()).read(TYPE, resolved);
String set = requiredText(props, "ConfigurationSetName");
JsonNode definition = props.path("EventDestination");
if (!definition.isObject()) {
throw invalid("EventDestination must be an object.");
}
validateNonblankRequiredValues(definition);
String explicitName = optionalText(definition, "Name");
Address prior = priorAddress(resource, ctx);
String name = explicitName != null && !explicitName.isBlank() ? explicitName
: prior != null && "generated".equals(resource.getAttributes().get(NAME_MODE_ATTR))
? prior.name() : ctx.generatePhysicalName(resource.getLogicalId(), 64, false);
Address target = new Address(set, name, ctx.region());
EventDestination destination = destination(definition, name);
deletePending(resource);
boolean replacement = prior == null || !prior.equals(target);
ObjectNode snapshot = ctx.isUpdate() ? snapshot(resource, prior, target, ctx) : null;
if (snapshot != null && !replacement) {
EventDestination previous = find(prior);
snapshot.set("previous", MAPPER.valueToTree(previous));
resource.getAttributes().put(UPDATE_ATTR, snapshot.toString());
configurationSets.updateEventDestination(set, name, destination, ctx.accountId(), ctx.region(), true);
} else {
if (snapshot != null) {
resource.getAttributes().put(UPDATE_ATTR, snapshot.toString());
}
configurationSets.createEventDestination(set, name, destination, ctx.accountId(), ctx.region(), true);
if (snapshot != null) {
snapshot.put("created", true);
resource.getAttributes().put(UPDATE_ATTR, snapshot.toString());
if (prior != null) {
CfnLifecycleRecords.setCleanup(resource, CLEANUP_ATTR, address(prior), true);
}
}
}
resource.setPhysicalId(name);
resource.getAttributes().put("Id", name);
resource.getAttributes().put(SET_ATTR, set);
resource.getAttributes().put(NAME_MODE_ATTR, explicitName == null || explicitName.isBlank()
? "generated" : "explicit");
resource.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
}
private Address priorAddress(StackResource resource, ProvisionContext ctx) {
if (!ctx.isUpdate()) {
return null;
}
String set = resource.getAttributes().get(SET_ATTR);
if (set == null) {
if (!CfnResourceDispatcher.isStub(ctx.priorPhysicalId(), resource.getAttributes())) {
throw new IllegalStateException("Missing SES event destination address for "
+ resource.getLogicalId());
}
return null;
}
return new Address(set, ctx.priorPhysicalId(), ctx.region());
}
private EventDestination find(Address address) {
return configurationSets.getEventDestinations(address.set(), address.region()).stream()
.filter(destination -> address.name().equals(destination.getName()))
.findFirst().orElseThrow(() -> new AwsException("NotFoundException",
"SES event destination " + address.name() + " does not exist.", 404));
}
private static EventDestination destination(JsonNode definition, String name) {
ObjectNode normalized = ((ObjectNode) definition).deepCopy();
if (normalized.get("SnsDestination") instanceof ObjectNode sns) {
rename(sns, "TopicARN", "TopicArn");
}
if (normalized.get("KinesisFirehoseDestination") instanceof ObjectNode firehose) {
rename(firehose, "IAMRoleARN", "IamRoleArn");
rename(firehose, "DeliveryStreamARN", "DeliveryStreamArn");
}
try {
EventDestination destination = MAPPER.treeToValue(normalized, EventDestination.class);
destination.setName(name);
return destination;
} catch (JsonProcessingException failure) {
throw invalid("Invalid EventDestination: " + failure.getOriginalMessage());
}
}
private static void rejectNullDestinationBlocks(JsonNode definition) {
if (!definition.isObject()) {
return;
}
for (String key : new String[] {"SnsDestination", "KinesisFirehoseDestination",
"EventBridgeDestination", "CloudWatchDestination"}) {
if (definition.path(key).isNull()) {
throw invalid(key + " must be an object.");
}
}
if (definition.path("CloudWatchDestination").path("DimensionConfigurations").isNull()) {
throw invalid("DimensionConfigurations must be an array.");
}
JsonNode dimensions = definition.path("CloudWatchDestination").path("DimensionConfigurations");
if (dimensions.isArray()) {
for (JsonNode dimension : dimensions) {
if (dimension.isNull()) {
throw invalid("DimensionConfigurations entries must be objects.");
}
}
}
}
private static void validateNonblankRequiredValues(JsonNode definition) {
// HandlerReader checks schema types and missing members; these reject blank strings and nulls it omits.
if (!definition.has("MatchingEventTypes")) {
throw invalid("MatchingEventTypes is required.");
}
if (definition.path("SnsDestination").isObject()) {
requiredText(definition.get("SnsDestination"), "TopicARN");
}
if (definition.path("KinesisFirehoseDestination").isObject()) {
requiredText(definition.get("KinesisFirehoseDestination"), "IAMRoleARN");
requiredText(definition.get("KinesisFirehoseDestination"), "DeliveryStreamARN");
}
if (definition.path("EventBridgeDestination").isObject()) {
requiredText(definition.get("EventBridgeDestination"), "EventBusArn");
}
JsonNode dimensions = definition.path("CloudWatchDestination").path("DimensionConfigurations");
if (dimensions.isArray()) {
for (JsonNode dimension : dimensions) {
requiredText(dimension, "DimensionName");
requiredText(dimension, "DimensionValueSource");
requiredText(dimension, "DefaultDimensionValue");
}
}
}
private static void rename(ObjectNode node, String from, String to) {
JsonNode value = node.remove(from);
if (value != null) {
node.set(to, value);
}
}
private static ObjectNode snapshot(StackResource resource, Address prior, Address target, ProvisionContext ctx) {
ObjectNode snapshot = MAPPER.createObjectNode();
snapshot.put("physicalId", resource.getPhysicalId());
snapshot.put("accountId", ctx.accountId());
snapshot.put("replacement", prior == null || !prior.equals(target));
snapshot.set("attributes", MAPPER.valueToTree(resource.getAttributes()));
snapshot.set("target", address(target));
if (prior != null) {
snapshot.set("prior", address(prior));
}
return snapshot;
}
private record Address(String set, String name, String region) { }
private static ObjectNode address(Address address) {
return MAPPER.createObjectNode().put("set", address.set()).put("name", address.name())
.put("region", address.region());
}
private static Address address(JsonNode node) {
return new Address(node.path("set").asText(), node.path("name").asText(),
node.path("region").asText());
}
private void delete(Address address) {
CfnDeletes.safeDelete("SES event destination", address.name(),
() -> configurationSets.deleteEventDestination(address.set(), address.name(), address.region()),
"NotFoundException", "ConfigurationSetDoesNotExist");
}
@Override
public void delete(StackResource resource, String region) {
ObjectNode snapshot = read(resource, UPDATE_ATTR);
if (snapshot != null && snapshot.path("replacement").asBoolean()
&& snapshot.path("created").asBoolean()) {
delete(address(snapshot.path("target")));
}
if (snapshot != null && snapshot.has("prior")) {
delete(address(snapshot.path("prior")));
} else if (snapshot == null && resource.getAttributes().containsKey(SET_ATTR)) {
delete(new Address(resource.getAttributes().get(SET_ATTR), resource.getPhysicalId(), region));
}
deletePending(resource);
resource.getAttributes().remove(UPDATE_ATTR);
}
private void deletePending(StackResource resource) {
ObjectNode pending = read(resource, CLEANUP_ATTR);
CfnLifecycleRecords.deletePending(resource, CLEANUP_ATTR, pending, true,
record -> delete(address(record)));
}
@Override
public boolean rollbackUpdate(StackResource resource) {
ObjectNode snapshot = read(resource, UPDATE_ATTR);
if (snapshot == null) {
return true;
}
if (snapshot.path("replacement").asBoolean()) {
if (snapshot.path("created").asBoolean()) {
delete(address(snapshot.path("target")));
}
resource.getAttributes().remove(CLEANUP_ATTR);
} else {
Address prior = address(snapshot.path("prior"));
try {
EventDestination previous = MAPPER.treeToValue(snapshot.path("previous"), EventDestination.class);
configurationSets.updateEventDestination(prior.set(), prior.name(), previous,
snapshot.path("accountId").asText(), prior.region(), true);
} catch (JsonProcessingException failure) {
throw new IllegalStateException("Invalid SES event destination update snapshot", failure);
}
}
resource.setPhysicalId(snapshot.path("physicalId").asText(null));
resource.getAttributes().clear();
snapshot.path("attributes").fields().forEachRemaining(entry ->
resource.getAttributes().put(entry.getKey(), entry.getValue().asText()));
return true;
}
@Override
public boolean retainsFailedUpdateState(StackResource resource) {
return resource.getAttributes().containsKey(UPDATE_ATTR);
}
@Override
public boolean requiresUpdateRecovery(StackResource resource) {
return "UPDATE_FAILED".equals(resource.getStatus()) && retainsFailedUpdateState(resource);
}
@Override
public boolean hasReplacementUpdate(StackResource resource) {
return resource.getAttributes().containsKey(CLEANUP_ATTR);
}
@Override
public String updateCleanupPhysicalId(StackResource resource) {
ObjectNode pending = read(resource, CLEANUP_ATTR);
return CfnLifecycleRecords.cleanupPhysicalId(resource, pending);
}
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
if (requiresUpdateRecovery(resource)) {
return new UpdateCleanupResult(true, false, resource.getPhysicalId(), 0,
"SES event destination rollback is pending.");
}
return completePending(resource);
}
private UpdateCleanupResult completePending(StackResource resource) {
ObjectNode pending = read(resource, CLEANUP_ATTR);
return CfnLifecycleRecords.completePending(resource, CLEANUP_ATTR, UPDATE_ATTR, pending, true,
record -> delete(address(record)));
}
@Override
public UpdateCleanupResult completeDeleteCleanup(StackResource resource) {
ObjectNode pending = read(resource, CLEANUP_ATTR);
if (pending == null) {
return UpdateCleanupResult.notApplicable();
}
return completePending(resource);
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(UPDATE_ATTR);
}
private static ObjectNode read(StackResource resource, String attribute) {
return CfnLifecycleRecords.read(resource, attribute,
"Invalid SES event destination lifecycle record",
"SES event destination lifecycle record must be an object");
}
private static String requiredText(JsonNode node, String key) {
String value = optionalText(node, key);
if (value == null || value.isBlank()) {
throw invalid(key + " must be a nonempty string.");
}
return value;
}
private static String optionalText(JsonNode node, String key) {
JsonNode value = node.get(key);
if (value == null || value.isNull()) {
return null;
}
if (!value.isTextual()) {
throw invalid(key + " must be a string.");
}
return value.textValue();
}
private static AwsException invalid(String message) {
return new AwsException("ValidationError", message, 400);
}
}
@@ -159,22 +159,13 @@ public class SesReceiptRuleCfnProvisioner implements CfnResourceProvisioner {
}
private static void setCleanup(StackResource resource, Identity identity, String region, boolean retainable) {
resource.getAttributes().put(CLEANUP_ATTR,
address(identity, region).put("retainable", retainable).put("attempts", 0).toString());
CfnLifecycleRecords.setCleanup(resource, CLEANUP_ATTR, address(identity, region), retainable);
}
private void deletePending(StackResource resource) {
ObjectNode pending = read(resource, CLEANUP_ATTR);
if (pending != null) {
if (!retained(resource, pending)) {
delete(identity(pending), pending.path("region").asText());
}
resource.getAttributes().remove(CLEANUP_ATTR);
}
}
private static boolean retained(StackResource resource, JsonNode pending) {
return pending.path("retainable").asBoolean() && "Retain".equals(resource.getUpdateReplacePolicy());
CfnLifecycleRecords.deletePending(resource, CLEANUP_ATTR, pending, true,
record -> delete(identity(record), record.path("region").asText()));
}
@Override
@@ -234,7 +225,7 @@ public class SesReceiptRuleCfnProvisioner implements CfnResourceProvisioner {
@Override
public String updateCleanupPhysicalId(StackResource resource) {
ObjectNode pending = read(resource, CLEANUP_ATTR);
return pending == null || retained(resource, pending) ? null : pending.path("name").asText();
return CfnLifecycleRecords.cleanupPhysicalId(resource, pending);
}
@Override
@@ -248,20 +239,8 @@ public class SesReceiptRuleCfnProvisioner implements CfnResourceProvisioner {
@Override
public UpdateCleanupResult completeDeleteCleanup(StackResource resource) {
ObjectNode pending = read(resource, CLEANUP_ATTR);
if (pending == null) {
return retainsFailedUpdateState(resource) ? new UpdateCleanupResult(true, true, null, 0, null)
: UpdateCleanupResult.notApplicable();
}
String name = pending.path("name").asText();
try {
deletePending(resource);
return new UpdateCleanupResult(true, true, name, 0, null);
} catch (RuntimeException failure) {
int attempts = pending.path("attempts").asInt() + 1;
pending.put("attempts", attempts);
resource.getAttributes().put(CLEANUP_ATTR, pending.toString());
return new UpdateCleanupResult(true, false, name, attempts, failure.getMessage());
}
return CfnLifecycleRecords.completePending(resource, CLEANUP_ATTR, UPDATE_ATTR, pending, true,
record -> delete(identity(record), record.path("region").asText()));
}
@Override
@@ -270,19 +249,8 @@ public class SesReceiptRuleCfnProvisioner implements CfnResourceProvisioner {
}
private static ObjectNode read(StackResource resource, String key) {
String raw = resource.getAttributes().get(key);
if (raw == null) {
return null;
}
try {
JsonNode node = MAPPER.readTree(raw);
if (node.isObject()) {
return (ObjectNode) node;
}
} catch (JsonProcessingException e) {
throw new IllegalStateException("Invalid SES receipt rule lifecycle record", e);
}
throw new IllegalStateException("Invalid SES receipt rule lifecycle record");
String error = "Invalid SES receipt rule lifecycle record";
return CfnLifecycleRecords.read(resource, key, error, error);
}
private static ReceiptRule parseRule(JsonNode node) {
+86 -2
View File
@@ -2,7 +2,7 @@
"_source": {
"generator": "tools/aws/regen_cfn_property_types.py",
"schemas": "https://schema.cloudformation.us-east-1.amazonaws.com/CloudformationSchema.zip",
"retrieved": "2026-11-14",
"retrieved": "2026-11-16",
"note": "make cfn-property-types-verify checks the file against AWS."
},
"operations": {
@@ -13,7 +13,8 @@
"AWS::ECS::TaskDefinition": "AWS::ECS::TaskDefinition",
"AWS::Events::Rule": "AWS::Events::Rule",
"AWS::Lambda::Function": "AWS::Lambda::Function",
"AWS::Lambda::LayerVersion": "AWS::Lambda::LayerVersion"
"AWS::Lambda::LayerVersion": "AWS::Lambda::LayerVersion",
"AWS::SES::ConfigurationSetEventDestination": "AWS::SES::ConfigurationSetEventDestination"
},
"shapes": {
"AWS::AutoScaling::LaunchConfiguration": {
@@ -2147,6 +2148,89 @@
"S3Key"
]
},
"AWS::SES::ConfigurationSetEventDestination": {
"type": "structure",
"members": {
"Id": "String",
"ConfigurationSetName": "String",
"EventDestination": "AWS::SES::ConfigurationSetEventDestination/EventDestination"
},
"required": [
"ConfigurationSetName",
"EventDestination"
]
},
"AWS::SES::ConfigurationSetEventDestination/CloudWatchDestination": {
"type": "structure",
"members": {
"DimensionConfigurations": "AWS::SES::ConfigurationSetEventDestination/CloudWatchDestination.DimensionConfigurations"
}
},
"AWS::SES::ConfigurationSetEventDestination/CloudWatchDestination.DimensionConfigurations": {
"type": "list",
"member": "AWS::SES::ConfigurationSetEventDestination/DimensionConfiguration"
},
"AWS::SES::ConfigurationSetEventDestination/DimensionConfiguration": {
"type": "structure",
"members": {
"DimensionValueSource": "String",
"DefaultDimensionValue": "String",
"DimensionName": "String"
},
"required": [
"DimensionValueSource",
"DefaultDimensionValue",
"DimensionName"
]
},
"AWS::SES::ConfigurationSetEventDestination/EventBridgeDestination": {
"type": "structure",
"members": {
"EventBusArn": "String"
},
"required": [
"EventBusArn"
]
},
"AWS::SES::ConfigurationSetEventDestination/EventDestination": {
"type": "structure",
"members": {
"Name": "String",
"Enabled": "Boolean",
"MatchingEventTypes": "AWS::SES::ConfigurationSetEventDestination/EventDestination.MatchingEventTypes",
"CloudWatchDestination": "AWS::SES::ConfigurationSetEventDestination/CloudWatchDestination",
"KinesisFirehoseDestination": "AWS::SES::ConfigurationSetEventDestination/KinesisFirehoseDestination",
"SnsDestination": "AWS::SES::ConfigurationSetEventDestination/SnsDestination",
"EventBridgeDestination": "AWS::SES::ConfigurationSetEventDestination/EventBridgeDestination"
},
"required": [
"MatchingEventTypes"
]
},
"AWS::SES::ConfigurationSetEventDestination/EventDestination.MatchingEventTypes": {
"type": "list",
"member": "String"
},
"AWS::SES::ConfigurationSetEventDestination/KinesisFirehoseDestination": {
"type": "structure",
"members": {
"IAMRoleARN": "String",
"DeliveryStreamARN": "String"
},
"required": [
"IAMRoleARN",
"DeliveryStreamARN"
]
},
"AWS::SES::ConfigurationSetEventDestination/SnsDestination": {
"type": "structure",
"members": {
"TopicARN": "String"
},
"required": [
"TopicARN"
]
},
"Boolean": {
"type": "boolean"
},
@@ -0,0 +1,5 @@
{
"AWS::SES::ConfigurationSetEventDestination": [
"EventDestination/Name"
]
}
@@ -908,6 +908,9 @@
"AWS::SES::ConfigurationSet": [
"Name"
],
"AWS::SES::ConfigurationSetEventDestination": [
"ConfigurationSetName"
],
"AWS::SES::EmailIdentity": [
"EmailIdentity"
],
@@ -1,6 +1,7 @@
package io.floci.aws.services.cloudformation;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
@@ -174,6 +175,37 @@ class CfnCreateOnlyPropertiesTest {
assertTrue(unknownProps.isEmpty());
}
@Test
void sesEventDestinationNameUsesConditionalReplacementMetadata() throws IOException {
String type = "AWS::SES::ConfigurationSetEventDestination";
assertEquals(Set.of("ConfigurationSetName"), CfnCreateOnlyProperties.getCreateOnlyProperties(type));
assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "EventDestination"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "Name"));
assertEquals(Set.of("ConfigurationSetName", "EventDestination/Name"),
CfnCreateOnlyProperties.replacementPointers(type));
ObjectMapper mapper = new ObjectMapper();
JsonNode previous = mapper.readTree("""
{"ConfigurationSetName":"set","EventDestination":{"Name":"old","Enabled":true}}
""");
JsonNode renamed = mapper.readTree("""
{"ConfigurationSetName":"set","EventDestination":{"Name":"new","Enabled":true}}
""");
JsonNode updated = mapper.readTree("""
{"ConfigurationSetName":"set","EventDestination":{"Name":"old","Enabled":false}}
""");
assertTrue(CfnCreateOnlyProperties.createOnlyValueChanged(type, previous, renamed));
assertFalse(CfnCreateOnlyProperties.createOnlyValueChanged(type, previous, updated));
assertEquals(Set.of(previous.path("ConfigurationSetName"), previous.path("EventDestination").path("Name")),
Set.copyOf(CfnCreateOnlyProperties.createOnlySubtrees(type, previous)));
try (InputStream in = getClass().getClassLoader()
.getResourceAsStream("cloudformation/conditional-create-only-properties.json")) {
assertEquals(Map.of(type, Set.of("EventDestination/Name")),
mapper.readValue(in, new TypeReference<Map<String, Set<String>>>() {}));
}
}
/**
* Every type floci provisions has an entry in create-only-properties.json, taken from its
* registry schema, so the name heuristic in {@code isCreateOnly} is never what answers for a
@@ -114,6 +114,7 @@ import io.floci.aws.services.cloudformation.provisioners.SchedulerScheduleGroupC
import io.floci.aws.services.cloudformation.provisioners.SecretTargetAttachmentCfnProvisioner;
import io.floci.aws.services.cloudformation.provisioners.SecretsManagerCfnProvisioner;
import io.floci.aws.services.cloudformation.provisioners.SesCfnProvisioner;
import io.floci.aws.services.cloudformation.provisioners.SesEventDestinationCfnProvisioner;
import io.floci.aws.services.cloudformation.provisioners.SesReceiptRuleCfnProvisioner;
import io.floci.aws.services.cloudformation.provisioners.SignerCfnProvisioner;
import io.floci.aws.services.cloudformation.provisioners.SnsCfnProvisioner;
@@ -173,6 +174,7 @@ import io.floci.aws.services.s3.S3Service;
import io.floci.aws.services.s3vectors.S3VectorsService;
import io.floci.aws.services.scheduler.SchedulerService;
import io.floci.aws.services.secretsmanager.SecretsManagerService;
import io.floci.aws.services.ses.SesConfigurationSetService;
import io.floci.aws.services.ses.SesIdentityService;
import io.floci.aws.services.ses.SesReceiptRuleService;
import io.floci.aws.services.ses.SesService;
@@ -228,6 +230,7 @@ final class CfnProvisionerFixture {
private S3VectorsService s3VectorsService;
private SnsService snsService;
private SesService sesService;
private SesConfigurationSetService sesConfigurationSetService;
private SesReceiptRuleService sesReceiptRuleService;
private SesIdentityService sesIdentityService;
private DynamoDbService dynamoDbService;
@@ -361,6 +364,9 @@ final class CfnProvisionerFixture {
if (sesService != null && sesIdentityService != null) {
discovered.add(new SesCfnProvisioner(sesService, sesIdentityService));
}
if (sesConfigurationSetService != null) {
discovered.add(new SesEventDestinationCfnProvisioner(sesConfigurationSetService));
}
if (sesReceiptRuleService != null && sesIdentityService != null) {
discovered.add(new SesReceiptRuleCfnProvisioner(sesReceiptRuleService, sesIdentityService));
}
@@ -605,6 +611,11 @@ final class CfnProvisionerFixture {
return this;
}
public Builder sesConfigurationSets(SesConfigurationSetService v) {
this.sesConfigurationSetService = v;
return this;
}
public Builder sesIdentity(SesIdentityService v) {
this.sesIdentityService = v;
return this;
@@ -8,6 +8,7 @@ import io.floci.aws.services.cloudformation.provisioners.ProvisionContext;
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsService;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.scheduler.SchedulerService;
import io.floci.aws.services.ses.SesConfigurationSetService;
import io.floci.aws.services.sns.SnsService;
import io.floci.aws.testing.MainSources;
import org.junit.jupiter.api.Test;
@@ -73,6 +74,14 @@ class CfnProvisionerFixtureTest {
assertTrue(serves(fixture, "AWS::Scheduler::ScheduleGroup"));
}
@Test
void sesConfigurationSetsWireEventDestinations() {
CfnProvisionerFixture.Builder fixture = CfnProvisionerFixture.builder()
.sesConfigurationSets(mock(SesConfigurationSetService.class));
assertTrue(serves(fixture, "AWS::SES::ConfigurationSetEventDestination"));
}
@Test
void anUnnamedServiceIsNotWired() {
CfnProvisionerFixture.Builder fixture = CfnProvisionerFixture.builder()
@@ -0,0 +1,292 @@
package io.floci.aws.services.cloudformation;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.services.ses.SesConfigurationSetService;
import io.floci.aws.services.ses.model.EventDestination;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.CfnStackWaits;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.ssm.SsmClient;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class CloudFormationSesEventDestinationIntegrationTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private CloudFormationClient cfn;
private String stackName;
private boolean deleted;
@Inject
SesConfigurationSetService configurationSets;
@BeforeEach
void setUp() {
cfn = AwsTestClients.create(CloudFormationClient.builder(), "test", Region.US_EAST_1);
stackName = "cfn-ses-ed-" + Long.toString(System.nanoTime(), 36);
deleted = false;
}
@AfterEach
void cleanUp() {
try {
if (!deleted) {
CfnStackWaits.deleteStack(cfn, stackName);
}
} finally {
cfn.close();
}
}
@Test
void eventDestinationFollowsConfigurationSetCreateUpdateAndRemoval() {
String setName = stackName + "-set";
String destinationName = stackName + "-events";
CfnStackWaits.createStack(cfn, stackName,
template(setName, destinationName, "SEND", "initial"), "CREATE_COMPLETE");
assertEquals(destinationName, cfn.describeStacks(request -> request.stackName(stackName))
.stacks().getFirst().outputs().stream()
.filter(output -> "DestinationId".equals(output.outputKey()))
.findFirst().orElseThrow().outputValue());
List<EventDestination> destinations = configurationSets.getEventDestinations(setName, "us-east-1");
assertEquals(1, destinations.size());
assertEquals(destinationName, destinations.getFirst().getName());
assertEquals(List.of("SEND"), destinations.getFirst().getMatchingEventTypes());
assertEquals("initial", destinations.getFirst().getCloudWatchDestination()
.getDimensionConfigurations().getFirst().getDefaultDimensionValue());
CfnStackWaits.updateStack(cfn, stackName,
template(setName, destinationName, "BOUNCE", "updated"), "UPDATE_COMPLETE");
destinations = configurationSets.getEventDestinations(setName, "us-east-1");
assertEquals(1, destinations.size());
assertEquals(destinationName, destinations.getFirst().getName());
assertEquals(List.of("BOUNCE"), destinations.getFirst().getMatchingEventTypes());
assertEquals("updated", destinations.getFirst().getCloudWatchDestination()
.getDimensionConfigurations().getFirst().getDefaultDimensionValue());
String replacementSet = stackName + "-new-set";
CfnStackWaits.updateStack(cfn, stackName,
template(replacementSet, destinationName, "BOUNCE", "updated"), "UPDATE_COMPLETE");
assertTrue(configurationSets.find(setName, "us-east-1").isEmpty());
assertEquals(destinationName, configurationSets.getEventDestinations(replacementSet, "us-east-1")
.getFirst().getName());
CfnStackWaits.updateStack(cfn, stackName, """
{"Resources": {"ConfigurationSet": {
"Type": "AWS::SES::ConfigurationSet", "Properties": {"Name": "%s"}
}}}
""".formatted(replacementSet), "UPDATE_COMPLETE");
assertTrue(configurationSets.getEventDestinations(replacementSet, "us-east-1").isEmpty());
CfnStackWaits.deleteStack(cfn, stackName);
deleted = true;
}
@Test
void changingTheDestinationNamePreviewsAndPerformsReplacement() {
String setName = stackName + "-set";
String oldName = stackName + "-old";
String newName = stackName + "-new";
CfnStackWaits.createStack(cfn, stackName,
template(setName, oldName, "SEND", "initial"), "CREATE_COMPLETE");
CfnStackTestSupport.createUpdateChangeSet(cfn, stackName, "rename",
template(setName, newName, "SEND", "initial"));
assertEquals(List.of("True"), CfnStackTestSupport.replacement(
cfn, stackName, "rename", "EventDestination"));
CfnStackTestSupport.executeAndAwaitUpdate(cfn, stackName, "rename");
assertEquals(List.of(newName), configurationSets.getEventDestinations(setName, "us-east-1")
.stream().map(EventDestination::getName).toList());
}
@Test
void changedDynamicDestinationNamePreviewsReplacement() {
String setName = stackName + "-set";
String oldName = stackName + "-old";
String newName = stackName + "-new";
String parameter = "/ses/event-destination/" + stackName;
String reference = "{{resolve:ssm:" + parameter + "}}";
try (SsmClient ssm = AwsTestClients.create(SsmClient.builder(), "test", Region.US_EAST_1)) {
try {
ssm.putParameter(request -> request.name(parameter).type("String").value(oldName));
CfnStackWaits.createStack(cfn, stackName,
template(setName, reference, "SEND", "initial"), "CREATE_COMPLETE");
ssm.putParameter(request -> request.name(parameter).type("String").value(newName)
.overwrite(true));
CfnStackTestSupport.createUpdateChangeSet(cfn, stackName, "rename-dynamic",
template(setName, reference, "BOUNCE", "initial"));
assertEquals(List.of("True"), CfnStackTestSupport.replacement(
cfn, stackName, "rename-dynamic", "EventDestination"));
CfnStackTestSupport.executeAndAwaitUpdate(cfn, stackName, "rename-dynamic");
assertEquals(List.of(newName), configurationSets.getEventDestinations(setName, "us-east-1")
.stream().map(EventDestination::getName).toList());
} catch (RuntimeException | Error failure) {
try {
ssm.deleteParameter(request -> request.name(parameter));
} catch (RuntimeException cleanupFailure) {
failure.addSuppressed(cleanupFailure);
}
throw failure;
}
ssm.deleteParameter(request -> request.name(parameter));
}
}
@Test
void dependentFailureRestoresAnInPlaceUpdate() throws JsonProcessingException {
String setName = stackName + "-set";
String destinationName = stackName + "-events";
CfnStackWaits.createStack(cfn, stackName,
template(setName, destinationName, "SEND", "initial"), "CREATE_COMPLETE");
String update = withBadDependent(template(setName, destinationName, "BOUNCE", "updated"));
CfnStackWaits.updateStack(cfn, stackName, update, "UPDATE_ROLLBACK_COMPLETE");
List<EventDestination> destinations = configurationSets.getEventDestinations(setName, "us-east-1");
assertEquals(1, destinations.size());
assertEquals(destinationName, destinations.getFirst().getName());
assertEquals(List.of("SEND"), destinations.getFirst().getMatchingEventTypes());
assertEquals("initial", destinations.getFirst().getCloudWatchDestination()
.getDimensionConfigurations().getFirst().getDefaultDimensionValue());
}
@Test
void dependentFailureRemovesAReplacementAndKeepsThePriorDestination() throws JsonProcessingException {
String setName = stackName + "-set";
String destinationName = stackName + "-events";
CfnStackWaits.createStack(cfn, stackName,
template(setName, destinationName, "SEND", "initial"), "CREATE_COMPLETE");
String update = withBadDependent(template(setName, destinationName + "-new", "BOUNCE", "updated"));
CfnStackWaits.updateStack(cfn, stackName, update, "UPDATE_ROLLBACK_COMPLETE");
List<EventDestination> destinations = configurationSets.getEventDestinations(setName, "us-east-1");
assertEquals(1, destinations.size());
assertEquals(destinationName, destinations.getFirst().getName());
assertEquals(List.of("SEND"), destinations.getFirst().getMatchingEventTypes());
}
@Test
void cloudFormationArnPropertiesMapToSesDestinationsAndEnabledDefaultsToFalse() {
String setName = stackName + "-set";
String roleArn = "arn:aws:iam::000000000000:role/ses-firehose";
String streamArn = "arn:aws:firehose:us-east-1:000000000000:deliverystream/ses-events";
try (SnsClient sns = AwsTestClients.create(SnsClient.builder(), "test", Region.US_EAST_1)) {
String topicArn = sns.createTopic(request -> request.name(stackName + "-topic")).topicArn();
try {
String template = """
{
"Resources": {
"ConfigurationSet": {
"Type": "AWS::SES::ConfigurationSet", "Properties": {"Name": "%s"}
},
"SnsEvents": {
"Type": "AWS::SES::ConfigurationSetEventDestination",
"Properties": {
"ConfigurationSetName": {"Ref": "ConfigurationSet"},
"EventDestination": {
"Name": "sns-events",
"MatchingEventTypes": ["SEND"],
"SnsDestination": {"TopicARN": "%s"}
}
}
},
"FirehoseEvents": {
"Type": "AWS::SES::ConfigurationSetEventDestination",
"Properties": {
"ConfigurationSetName": {"Ref": "ConfigurationSet"},
"EventDestination": {
"Name": "firehose-events",
"MatchingEventTypes": ["SEND"],
"KinesisFirehoseDestination": {
"IAMRoleARN": "%s", "DeliveryStreamARN": "%s"
}
}
}
}
}
}
""".formatted(setName, topicArn, roleArn, streamArn);
CfnStackWaits.createStack(cfn, stackName, template, "CREATE_COMPLETE");
List<EventDestination> destinations = configurationSets.getEventDestinations(setName, "us-east-1");
assertEquals(2, destinations.size());
EventDestination snsDestination = destinations.stream()
.filter(destination -> "sns-events".equals(destination.getName()))
.findFirst().orElseThrow();
EventDestination firehoseDestination = destinations.stream()
.filter(destination -> "firehose-events".equals(destination.getName()))
.findFirst().orElseThrow();
assertFalse(snsDestination.isEnabled());
assertEquals(topicArn, snsDestination.getSnsDestination().getTopicArn());
assertEquals(roleArn, firehoseDestination.getKinesisFirehoseDestination().getIamRoleArn());
assertEquals(streamArn, firehoseDestination.getKinesisFirehoseDestination().getDeliveryStreamArn());
} finally {
sns.deleteTopic(request -> request.topicArn(topicArn));
}
}
}
private String withBadDependent(String template) throws JsonProcessingException {
ObjectNode root = (ObjectNode) MAPPER.readTree(template);
ObjectNode badSecret = ((ObjectNode) root.path("Resources")).putObject("BadSecret");
badSecret.put("Type", "AWS::SecretsManager::Secret");
badSecret.put("DependsOn", "EventDestination");
ObjectNode properties = badSecret.putObject("Properties");
properties.put("SecretString", "conflicting");
properties.putObject("GenerateSecretString").put("PasswordLength", 8);
return root.toString();
}
private String template(String setName, String destinationName, String eventType, String defaultValue) {
return """
{
"Resources": {
"ConfigurationSet": {
"Type": "AWS::SES::ConfigurationSet",
"Properties": {"Name": "%s"}
},
"EventDestination": {
"Type": "AWS::SES::ConfigurationSetEventDestination",
"Properties": {
"ConfigurationSetName": {"Ref": "ConfigurationSet"},
"EventDestination": {
"Name": "%s",
"Enabled": true,
"MatchingEventTypes": ["%s"],
"CloudWatchDestination": {
"DimensionConfigurations": [{
"DimensionName": "campaign",
"DimensionValueSource": "messageTag",
"DefaultDimensionValue": "%s"
}]
}
}
}
}
},
"Outputs": {
"DestinationId": {"Value": {"Fn::GetAtt": ["EventDestination", "Id"]}}
}
}
""".formatted(setName, destinationName, eventType, defaultValue);
}
}
@@ -0,0 +1,248 @@
package io.floci.aws.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.ses.SesConfigurationSetService;
import io.floci.aws.services.ses.model.EventDestination;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.function.UnaryOperator;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class SesEventDestinationCfnProvisionerTest {
private static final String ACCOUNT = "000000000000";
private static final String REGION = "us-east-1";
private final ObjectMapper mapper = new ObjectMapper();
private final SesConfigurationSetService configurationSets = mock(SesConfigurationSetService.class);
private final SesEventDestinationCfnProvisioner provisioner =
new SesEventDestinationCfnProvisioner(configurationSets);
@Test
void failedReplacementRollbackRetriesBeforeTheNextUpdateUsesTheRestoredPhysicalId() {
StackResource resource = resource();
provisioner.provision(resource, properties("first", "old", false), context(null));
provisioner.provision(resource, properties("second", "new", true), context("old"));
resource.setStatus("UPDATE_FAILED");
doThrow(new AwsException("InternalFailure", "retry deletion", 500)).doNothing()
.when(configurationSets).deleteEventDestination("second", "new", REGION);
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(resource));
assertTrue(provisioner.requiresUpdateRecovery(resource));
assertEquals("new", resource.getPhysicalId());
EventDestination previous = new EventDestination();
previous.setName("old");
previous.setMatchingEventTypes(List.of("SEND"));
when(configurationSets.getEventDestinations("first", REGION)).thenReturn(List.of(previous));
// The stack can still pass the failed replacement's id as the prior id on this call.
provisioner.provision(resource, properties("first", "old", true), context("new"));
assertEquals("old", resource.getPhysicalId());
assertEquals("old", resource.getAttributes().get("Id"));
verify(configurationSets, times(2)).deleteEventDestination("second", "new", REGION);
verify(configurationSets).updateEventDestination(eq("first"), eq("old"), any(EventDestination.class),
eq(ACCOUNT), eq(REGION), eq(true));
verify(configurationSets, times(1)).createEventDestination(eq("first"), eq("old"),
any(EventDestination.class), eq(ACCOUNT), eq(REGION), eq(true));
}
@Test
void retainedReplacementWithTheSameNameKeepsTheOldConfigurationSetDestination() {
StackResource resource = resource();
provisioner.provision(resource, properties("first", "shared", false), context(null));
resource.setUpdateReplacePolicy("Retain");
provisioner.provision(resource, properties("second", "shared", true), context("shared"));
assertTrue(provisioner.hasReplacementUpdate(resource));
assertNull(provisioner.updateCleanupPhysicalId(resource));
assertTrue(provisioner.completeUpdate(resource).complete());
assertFalse(provisioner.hasReplacementUpdate(resource));
provisioner.clearUpdate(resource);
provisioner.delete(resource, REGION);
verify(configurationSets).deleteEventDestination("second", "shared", REGION);
verify(configurationSets, never()).deleteEventDestination("first", "shared", REGION);
}
@Test
void rejectsUnsupportedNestedDestinationProperties() {
ObjectNode props = properties("first", "events", true);
props.withObject("EventDestination").putObject("SnsDestination")
.put("TopicARN", "arn:aws:sns:us-east-1:000000000000:events")
.put("Unexpected", "ignored");
assertThrows(AwsException.class, () -> provisioner.provision(resource(), props, context(null)));
verify(configurationSets, never()).createEventDestination(eq("first"), eq("events"),
any(EventDestination.class), eq(ACCOUNT), eq(REGION), eq(true));
}
@Test
void rejectsMissingAndBlankSnsTopicArnBeforeCallingSes() {
ObjectNode missing = properties("first", "events", true);
missing.withObject("EventDestination").putObject("SnsDestination");
assertSchemaInvalidWithoutSesCall(missing);
ObjectNode blank = properties("first", "events", true);
blank.withObject("EventDestination").putObject("SnsDestination").put("TopicARN", " ");
assertInvalidWithoutSesCall(blank);
}
@Test
void rejectsMissingAndBlankFirehoseArnsBeforeCallingSes() {
ObjectNode missing = properties("first", "events", true);
missing.withObject("EventDestination").putObject("KinesisFirehoseDestination")
.put("IAMRoleARN", "arn:aws:iam::000000000000:role/ses");
assertSchemaInvalidWithoutSesCall(missing);
ObjectNode blank = properties("first", "events", true);
blank.withObject("EventDestination").putObject("KinesisFirehoseDestination")
.put("IAMRoleARN", " ")
.put("DeliveryStreamARN", "arn:aws:firehose:us-east-1:000000000000:deliverystream/events");
assertInvalidWithoutSesCall(blank);
}
@Test
void rejectsMissingAndBlankEventBusArnBeforeCallingSes() {
ObjectNode missing = properties("first", "events", true);
missing.withObject("EventDestination").putObject("EventBridgeDestination");
assertSchemaInvalidWithoutSesCall(missing);
ObjectNode blank = properties("first", "events", true);
blank.withObject("EventDestination").putObject("EventBridgeDestination").put("EventBusArn", " ");
assertInvalidWithoutSesCall(blank);
}
@Test
void rejectsMissingConfigurationSetNameAndNonObjectDestinationsBeforeCallingSes() {
ObjectNode missingSet = properties("first", "events", true);
missingSet.remove("ConfigurationSetName");
assertSchemaInvalidWithoutSesCall(missingSet);
ObjectNode blankSet = properties("first", "events", true).put("ConfigurationSetName", " ");
assertInvalidWithoutSesCall(blankSet);
ObjectNode nonObjectDestination = properties("first", "events", true)
.put("EventDestination", "events");
assertSchemaInvalidWithoutSesCall(nonObjectDestination);
ObjectNode nonObjectBlock = properties("first", "events", true);
nonObjectBlock.withObject("EventDestination").put("SnsDestination", "topic");
assertSchemaInvalidWithoutSesCall(nonObjectBlock);
}
@Test
void rejectsMalformedCloudWatchDimensionsBeforeCallingSes() {
ObjectNode nonArray = properties("first", "events", true);
nonArray.withObject("EventDestination").putObject("CloudWatchDestination")
.put("DimensionConfigurations", "dimension");
assertSchemaInvalidWithoutSesCall(nonArray);
ObjectNode nonObjectEntry = properties("first", "events", true);
nonObjectEntry.withObject("EventDestination").putObject("CloudWatchDestination")
.putArray("DimensionConfigurations").add("dimension");
assertSchemaInvalidWithoutSesCall(nonObjectEntry);
}
@Test
void rejectsSchemaRequiredDestinationMembersBeforeCallingSes() {
ObjectNode missingEvents = properties("first", "events", true);
missingEvents.withObject("EventDestination").remove("MatchingEventTypes");
assertSchemaInvalidWithoutSesCall(missingEvents);
ObjectNode missingDimensionName = properties("first", "events", true);
missingDimensionName.withObject("EventDestination").putObject("CloudWatchDestination")
.putArray("DimensionConfigurations").addObject()
.put("DimensionValueSource", "messageTag")
.put("DefaultDimensionValue", "unknown");
assertSchemaInvalidWithoutSesCall(missingDimensionName);
}
@Test
void rejectsNullRequiredMembersAndDimensionEntriesBeforeCallingSes() {
ObjectNode nullEvents = properties("first", "events", true);
nullEvents.withObject("EventDestination").putNull("MatchingEventTypes");
assertInvalidWithoutSesCall(nullEvents);
ObjectNode nullTopic = properties("first", "events", true);
nullTopic.withObject("EventDestination").putObject("SnsDestination").putNull("TopicARN");
assertInvalidWithoutSesCall(nullTopic);
ObjectNode nullDimensionName = properties("first", "events", true);
nullDimensionName.withObject("EventDestination").putObject("CloudWatchDestination")
.putArray("DimensionConfigurations").addObject()
.put("DimensionValueSource", "messageTag")
.put("DefaultDimensionValue", "unknown")
.putNull("DimensionName");
assertInvalidWithoutSesCall(nullDimensionName);
ObjectNode nullDimensionEntry = properties("first", "events", true);
nullDimensionEntry.withObject("EventDestination").putObject("CloudWatchDestination")
.putArray("DimensionConfigurations").addNull();
assertInvalidWithoutSesCall(nullDimensionEntry);
}
@Test
void rejectsReadOnlySchemaIdBeforeCallingSes() {
ObjectNode props = properties("first", "events", true).put("Id", "read-only");
assertInvalidWithoutSesCall(props);
}
private void assertSchemaInvalidWithoutSesCall(ObjectNode props) {
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.provision(resource(), props, context(null)));
assertEquals("InvalidRequest", failure.getErrorCode());
assertEquals(400, failure.getHttpStatus());
verifyNoInteractions(configurationSets);
}
private void assertInvalidWithoutSesCall(ObjectNode props) {
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.provision(resource(), props, context(null)));
assertEquals("ValidationError", failure.getErrorCode());
assertEquals(400, failure.getHttpStatus());
verifyNoInteractions(configurationSets);
}
private ObjectNode properties(String set, String name, boolean enabled) {
ObjectNode props = mapper.createObjectNode().put("ConfigurationSetName", set);
ObjectNode destination = props.putObject("EventDestination");
destination.put("Name", name);
destination.put("Enabled", enabled);
destination.putArray("MatchingEventTypes").add("SEND");
return props;
}
private static StackResource resource() {
StackResource resource = new StackResource();
resource.setResourceType("AWS::SES::ConfigurationSetEventDestination");
resource.setLogicalId("EventDestination");
return resource;
}
private ProvisionContext context(String prior) {
CloudFormationTemplateEngine engine = CloudFormationTemplateEngine.standalone(ACCOUNT, REGION,
"stack", mapper, UnaryOperator.identity());
return new ProvisionContext(engine, REGION, ACCOUNT, "stack", prior);
}
}
@@ -186,6 +186,7 @@ AWS::S3::BucketPolicy Bucket,PolicyDocument
AWS::S3Vectors::Index CreationTime,IndexArn DataType,Dimension,DistanceMetric,EncryptionConfiguration,IndexName,MetadataConfiguration,Tags,VectorBucketArn,VectorBucketName
AWS::S3Vectors::VectorBucket CreationTime,VectorBucketArn EncryptionConfiguration,Tags,VectorBucketName
AWS::SES::ConfigurationSet ArchivingOptions,DeliveryOptions,Name,ReputationOptions,SendingOptions,SuppressionOptions,Tags,TrackingOptions,VdmOptions
AWS::SES::ConfigurationSetEventDestination Id ConfigurationSetName,EventDestination
AWS::SES::EmailIdentity DkimDNSTokenName1,DkimDNSTokenName2,DkimDNSTokenName3,DkimDNSTokenValue1,DkimDNSTokenValue2,DkimDNSTokenValue3 ConfigurationSetAttributes,DkimAttributes,DkimSigningAttributes,EmailIdentity,FeedbackAttributes,MailFromAttributes,Tags
AWS::SES::ReceiptRule RuleName After,Rule,RuleSetName
AWS::SNS::Subscription Arn DeliveryPolicy,Endpoint,FilterPolicy,FilterPolicyScope,Protocol,RawMessageDelivery,RedrivePolicy,Region,ReplayPolicy,SubscriptionRoleArn,TopicArn
1 AWS::ApiGateway::Account Id CloudWatchRoleArn
186 AWS::S3Vectors::Index CreationTime,IndexArn DataType,Dimension,DistanceMetric,EncryptionConfiguration,IndexName,MetadataConfiguration,Tags,VectorBucketArn,VectorBucketName
187 AWS::S3Vectors::VectorBucket CreationTime,VectorBucketArn EncryptionConfiguration,Tags,VectorBucketName
188 AWS::SES::ConfigurationSet ArchivingOptions,DeliveryOptions,Name,ReputationOptions,SendingOptions,SuppressionOptions,Tags,TrackingOptions,VdmOptions
189 AWS::SES::ConfigurationSetEventDestination Id ConfigurationSetName,EventDestination
190 AWS::SES::EmailIdentity DkimDNSTokenName1,DkimDNSTokenName2,DkimDNSTokenName3,DkimDNSTokenValue1,DkimDNSTokenValue2,DkimDNSTokenValue3 ConfigurationSetAttributes,DkimAttributes,DkimSigningAttributes,EmailIdentity,FeedbackAttributes,MailFromAttributes,Tags
191 AWS::SES::ReceiptRule RuleName After,Rule,RuleSetName
192 AWS::SNS::Subscription Arn DeliveryPolicy,Endpoint,FilterPolicy,FilterPolicyScope,Protocol,RawMessageDelivery,RedrivePolicy,Region,ReplayPolicy,SubscriptionRoleArn,TopicArn
@@ -187,6 +187,7 @@ AWS::S3::BucketPolicy S3CfnProvisioner
AWS::S3Vectors::Index S3VectorsCfnProvisioner
AWS::S3Vectors::VectorBucket S3VectorsCfnProvisioner
AWS::SES::ConfigurationSet SesCfnProvisioner
AWS::SES::ConfigurationSetEventDestination SesEventDestinationCfnProvisioner
AWS::SES::EmailIdentity SesCfnProvisioner
AWS::SES::ReceiptRule SesReceiptRuleCfnProvisioner
AWS::SNS::Subscription SnsCfnProvisioner
1 AWS::ApiGateway::Account ApiGatewayAccountCfnProvisioner
187 AWS::S3Vectors::Index S3VectorsCfnProvisioner
188 AWS::S3Vectors::VectorBucket S3VectorsCfnProvisioner
189 AWS::SES::ConfigurationSet SesCfnProvisioner
190 AWS::SES::ConfigurationSetEventDestination SesEventDestinationCfnProvisioner
191 AWS::SES::EmailIdentity SesCfnProvisioner
192 AWS::SES::ReceiptRule SesReceiptRuleCfnProvisioner
193 AWS::SNS::Subscription SnsCfnProvisioner