From 5f77b841a246e4e259ceae76c335aae5cfef3be4 Mon Sep 17 00:00:00 2001 From: Jimmy Liu Jia <91264074+JimmyLiuJia@users.noreply.github.com> Date: Tue, 17 Nov 2026 05:08:48 +0800 Subject: [PATCH] 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 --- docs/services/cloudformation.md | 2 +- .../CfnCreateOnlyProperties.java | 30 +- .../cloudformation/CloudFormationService.java | 2 +- .../provisioners/CfnLifecycleRecords.java | 76 ++++ .../provisioners/CfnPropertyTypes.java | 29 ++ .../LogsLogStreamCfnProvisioner.java | 52 +-- .../SesEventDestinationCfnProvisioner.java | 349 ++++++++++++++++++ .../SesReceiptRuleCfnProvisioner.java | 48 +-- .../resources/aws/cfn-property-types.json | 88 ++++- .../conditional-create-only-properties.json | 5 + .../create-only-properties.json | 3 + .../CfnCreateOnlyPropertiesTest.java | 32 ++ .../cloudformation/CfnProvisionerFixture.java | 11 + .../CfnProvisionerFixtureTest.java | 9 + ...ionSesEventDestinationIntegrationTest.java | 292 +++++++++++++++ ...SesEventDestinationCfnProvisionerTest.java | 248 +++++++++++++ .../cloudformation/schema-surface.tsv | 1 + .../supported-resource-types.tsv | 1 + tools/aws/regen_cfn_create_only.py | 39 +- tools/aws/regen_cfn_property_types.py | 12 +- tools/aws/test_regen_cfn_create_only.py | 24 +- tools/aws/test_regen_cfn_property_types.py | 15 + 22 files changed, 1264 insertions(+), 104 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnLifecycleRecords.java create mode 100644 src/main/java/io/floci/aws/services/cloudformation/provisioners/SesEventDestinationCfnProvisioner.java create mode 100644 src/main/resources/cloudformation/conditional-create-only-properties.json create mode 100644 src/test/java/io/floci/aws/services/cloudformation/CloudFormationSesEventDestinationIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudformation/provisioners/SesEventDestinationCfnProvisionerTest.java diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 956b2e9bf6..80c34f6de4 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -207,7 +207,7 @@ cross-resource references. | S3 Vectors | `VectorBucket`, `Index` | | SQS | `Queue`, `QueuePolicy` (accepted; policy not enforced) | | SNS | `Topic`, `Subscription`, `TopicPolicy` | -| SES | `ConfigurationSet` (only `Name` is supported; option and tag properties fail validation instead of being silently ignored; Ref returns the set name), `EmailIdentity` (BYODKIM is not supported by this resource; Easy DKIM DNS attributes use the shared emulator signing zone `dkim.amazonses.com` rather than AWS's region- and identity-specific zone assignment), `ReceiptRule` (stored in an existing SES receipt rule set; Ref and RuleName return the rule name; management plane only, with no inbound mail delivery) | +| SES | `ConfigurationSet` (only `Name` is supported; option and tag properties fail validation instead of being silently ignored; Ref returns the set name), `ConfigurationSetEventDestination`, `EmailIdentity` (BYODKIM is not supported by this resource; Easy DKIM DNS attributes use the shared emulator signing zone `dkim.amazonses.com` rather than AWS's region- and identity-specific zone assignment), `ReceiptRule` (stored in an existing SES receipt rule set; Ref and RuleName return the rule name; management plane only, with no inbound mail delivery) | | DynamoDB | `Table` (`TimeToLiveSpecification` applied on create and update; to rename an enabled TTL attribute, disable TTL in one update and enable the new attribute in a later one. `KinesisStreamSpecification` applied on create and update; with the DynamoDB Local backend, `StreamArn` is checked as on AWS but nothing is forwarded), `GlobalTable` | | Lambda | `Function` (Zip via S3/inline `ZipFile`, Image, and the `hot-reload` bind-mount bucket), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams; `ParallelizationFactor` and `TumblingWindowInSeconds` are ignored), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into), `Permission`, `CodeSigningConfig`, `EventInvokeConfig` (also what a SAM function's `EventInvokeConfig` expands into), `MicrovmImage`, `NetworkConnector`, `Url`, `WebFunction` (control plane only; the endpoint domain does not serve requests yet), `WebFunctionEndpoint`, `WebFunctionRevision` (every property is createOnly, so a change mints a new revision). Inline `ZipFile` packages include the `cfn-response` (Node.js) / `cfnresponse` (Python) module AWS injects for that code path, so Solutions-style custom-resource handlers work. | | Signer | `SigningProfile` (identifiers only; Floci has no Signer API) | diff --git a/src/main/java/io/floci/aws/services/cloudformation/CfnCreateOnlyProperties.java b/src/main/java/io/floci/aws/services/cloudformation/CfnCreateOnlyProperties.java index 34b7f91dd9..c455839559 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/CfnCreateOnlyProperties.java +++ b/src/main/java/io/floci/aws/services/cloudformation/CfnCreateOnlyProperties.java @@ -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> PROPERTIES = load(); + private static final String CONDITIONAL_RESOURCE_NAME = + "cloudformation/conditional-create-only-properties.json"; + private static final Map> PROPERTIES = load(RESOURCE_NAME); + private static final Map> CONDITIONAL_PROPERTIES = load(CONDITIONAL_RESOURCE_NAME); private CfnCreateOnlyProperties() { } - private static Map> load() { - try (InputStream in = CfnCreateOnlyProperties.class.getClassLoader().getResourceAsStream(RESOURCE_NAME)) { + private static Map> 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>>() {}); } 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 replacementPointers(String resourceType) { + Set schemaPointers = getCreateOnlyProperties(resourceType); + Set conditionalPointers = CONDITIONAL_PROPERTIES.get(resourceType); + if (conditionalPointers == null || conditionalPointers.isEmpty()) { + return schemaPointers; + } + Set 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 createOnlySubtrees(String resourceType, JsonNode props) { List out = new ArrayList<>(); - for (String pointer : getCreateOnlyProperties(resourceType)) { + for (String pointer : replacementPointers(resourceType)) { collect(props, pointer.split("/"), 0, out); } return out; diff --git a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java index db4596fbca..a61fc32188 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java @@ -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); diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnLifecycleRecords.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnLifecycleRecords.java new file mode 100644 index 0000000000..8ba45869ef --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnLifecycleRecords.java @@ -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 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 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()); + } + } +} diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnPropertyTypes.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnPropertyTypes.java index d32e2da3d0..e82f104177 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnPropertyTypes.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnPropertyTypes.java @@ -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"); diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/LogsLogStreamCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/LogsLogStreamCfnProvisioner.java index 8e2efd2b01..8e31499cf1 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/LogsLogStreamCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/LogsLogStreamCfnProvisioner.java @@ -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); } } diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/SesEventDestinationCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/SesEventDestinationCfnProvisioner.java new file mode 100644 index 0000000000..fc17a87079 --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/SesEventDestinationCfnProvisioner.java @@ -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 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); + } +} diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/SesReceiptRuleCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/SesReceiptRuleCfnProvisioner.java index 93ca8d8208..5f778c16d6 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/SesReceiptRuleCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/SesReceiptRuleCfnProvisioner.java @@ -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) { diff --git a/src/main/resources/aws/cfn-property-types.json b/src/main/resources/aws/cfn-property-types.json index 074a18278f..999caa0796 100644 --- a/src/main/resources/aws/cfn-property-types.json +++ b/src/main/resources/aws/cfn-property-types.json @@ -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" }, diff --git a/src/main/resources/cloudformation/conditional-create-only-properties.json b/src/main/resources/cloudformation/conditional-create-only-properties.json new file mode 100644 index 0000000000..0caf1b0ba5 --- /dev/null +++ b/src/main/resources/cloudformation/conditional-create-only-properties.json @@ -0,0 +1,5 @@ +{ + "AWS::SES::ConfigurationSetEventDestination": [ + "EventDestination/Name" + ] +} diff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.json index c61e3169ce..d3c39754e5 100644 --- a/src/main/resources/cloudformation/create-only-properties.json +++ b/src/main/resources/cloudformation/create-only-properties.json @@ -908,6 +908,9 @@ "AWS::SES::ConfigurationSet": [ "Name" ], + "AWS::SES::ConfigurationSetEventDestination": [ + "ConfigurationSetName" + ], "AWS::SES::EmailIdentity": [ "EmailIdentity" ], diff --git a/src/test/java/io/floci/aws/services/cloudformation/CfnCreateOnlyPropertiesTest.java b/src/test/java/io/floci/aws/services/cloudformation/CfnCreateOnlyPropertiesTest.java index a525abe0a3..a1e6895539 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CfnCreateOnlyPropertiesTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CfnCreateOnlyPropertiesTest.java @@ -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>>() {})); + } + } + /** * 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 diff --git a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java index a8f1ada8bd..e88b556b5c 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java @@ -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; diff --git a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixtureTest.java b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixtureTest.java index a4ea0f240e..edce31cf13 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixtureTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixtureTest.java @@ -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() diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationSesEventDestinationIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationSesEventDestinationIntegrationTest.java new file mode 100644 index 0000000000..8fced9d15a --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationSesEventDestinationIntegrationTest.java @@ -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 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 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 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 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); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/SesEventDestinationCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/SesEventDestinationCfnProvisionerTest.java new file mode 100644 index 0000000000..1fd6040d7f --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/SesEventDestinationCfnProvisionerTest.java @@ -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); + } +} diff --git a/src/test/resources/cloudformation/schema-surface.tsv b/src/test/resources/cloudformation/schema-surface.tsv index c16783f9b8..17f7f0dc0b 100644 --- a/src/test/resources/cloudformation/schema-surface.tsv +++ b/src/test/resources/cloudformation/schema-surface.tsv @@ -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 diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 516e127672..4965369832 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -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 diff --git a/tools/aws/regen_cfn_create_only.py b/tools/aws/regen_cfn_create_only.py index bda9e0304e..74502c326d 100644 --- a/tools/aws/regen_cfn_create_only.py +++ b/tools/aws/regen_cfn_create_only.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Regenerate src/main/resources/cloudformation/create-only-properties.json from CloudFormation's resource schemas. +"""Regenerate CloudFormation create-only property metadata from the published resource schemas. `CfnCreateOnlyProperties` answers, for a change set, whether editing a property replaces the resource. For a resource type with an entry the answer is the type's `createOnlyProperties` in the CloudFormation @@ -13,6 +13,10 @@ no create-only property (the class treats an empty entry as authoritative, not a with no schema in the archive has no entry and is declared in SCHEMALESS, which is the set `regen_cfn_schema_surface.py` holds; any other inventory type without a schema fails the run by name. +`conditional-create-only-properties.json` keeps conditional pointers separately for provisioners +that implement their replacement semantics. Other conditional schema pointers do not automatically +force replacement in Floci. + The schemas are the ones AWS publishes for us-east-1, the same `describe-type` returns: https://schema.cloudformation.us-east-1.amazonaws.com/CloudformationSchema.zip @@ -40,17 +44,21 @@ from regen_cfn_schema_surface import SCHEMALESS, file_name, inventory_types REPO_ROOT = Path(__file__).resolve().parents[2] OUTPUT = REPO_ROOT / "src/main/resources/cloudformation/create-only-properties.json" +CONDITIONAL_OUTPUT = REPO_ROOT / "src/main/resources/cloudformation/conditional-create-only-properties.json" INVENTORY = REPO_ROOT / "src/test/resources/cloudformation/supported-resource-types.tsv" ARCHIVE_URL = "https://schema.cloudformation.us-east-1.amazonaws.com/CloudformationSchema.zip" FETCH_TIMEOUT_SECONDS = 60 POINTER_PREFIX = "/properties/" +# Conditional pointers require resource-specific replacement semantics. Only this type has +# a provisioner that treats its named destination's change as replacement. +CONDITIONAL_REPLACEMENT_TYPES = {"AWS::SES::ConfigurationSetEventDestination"} -def create_only(schema: dict) -> list[str]: - """The schema's `createOnlyProperties` without the `/properties/` prefix, in the schema's order.""" - pointers = schema.get("createOnlyProperties", []) +def property_paths(schema: dict, key: str) -> list[str]: + """The schema's property pointers without the `/properties/` prefix, in schema order.""" + pointers = schema.get(key, []) if not isinstance(pointers, list): - raise ValueError("'createOnlyProperties' is not a list") + raise ValueError(f"{key!r} is not a list") names = [] for pointer in pointers: if not isinstance(pointer, str) or not pointer.startswith(POINTER_PREFIX) \ @@ -60,6 +68,10 @@ def create_only(schema: dict) -> list[str]: return names +def create_only(schema: dict) -> list[str]: + return property_paths(schema, "createOnlyProperties") + + def check_schema(resource_type: str, schema: object) -> None: """Refuse a schema that is not the one for `resource_type`, so a stub or renamed file cannot pass as empty.""" if not isinstance(schema, dict): @@ -93,6 +105,12 @@ def render(schemas: dict[str, dict]) -> str: return json.dumps(document, indent=2) + "\n" +def render_conditional(schemas: dict[str, dict]) -> str: + document = {resource_type: property_paths(schemas[resource_type], "conditionalCreateOnlyProperties") + for resource_type in sorted(schemas) if resource_type in CONDITIONAL_REPLACEMENT_TYPES} + return json.dumps(document, indent=2) + "\n" + + def _shown(path: Path) -> Path: try: return path.resolve().relative_to(REPO_ROOT) @@ -106,8 +124,10 @@ def main(argv: list[str] | None = None) -> int: parser.add_argument("--source-dir", type=Path, default=None, help="read saved aws--.json schemas instead of fetching the archive") parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS) + parser.add_argument("--conditional-output", type=Path, default=None, help=argparse.SUPPRESS) parser.add_argument("--inventory", type=Path, default=INVENTORY, help=argparse.SUPPRESS) args = parser.parse_args(argv) + conditional_output = args.conditional_output or args.output.with_name(CONDITIONAL_OUTPUT.name) resource_types = inventory_types(args.inventory) try: @@ -127,19 +147,24 @@ def main(argv: list[str] | None = None) -> int: for resource_type in sorted(schemas): check_schema(resource_type, schemas[resource_type]) document = render(schemas) + conditional_document = render_conditional(schemas) except (AttributeError, TypeError, ValueError) as e: print(f"error: could not read the CloudFormation resource schemas ({e})", file=sys.stderr) return 2 if args.verify: - if not args.output.exists() or args.output.read_text(encoding="utf-8") != document: - print(f"error: {_shown(args.output)} no longer matches {provenance}; run " + if (not args.output.exists() or args.output.read_text(encoding="utf-8") != document + or not conditional_output.exists() + or conditional_output.read_text(encoding="utf-8") != conditional_document): + print(f"error: {_shown(args.output)} or {_shown(conditional_output)} no longer matches " + f"{provenance}; run " f"'make cfn-create-only-sync' and commit the result.", file=sys.stderr) return 1 print(f"{_shown(args.output)} matches {provenance}.") return 0 args.output.write_text(document, encoding="utf-8") + conditional_output.write_text(conditional_document, encoding="utf-8") print(f"wrote {_shown(args.output)} ({len(schemas)} types, from {provenance}); " f"no schema: {', '.join(schemaless) if schemaless else 'none'}") return 0 diff --git a/tools/aws/regen_cfn_property_types.py b/tools/aws/regen_cfn_property_types.py index 80ad47e5de..debca8ed75 100644 --- a/tools/aws/regen_cfn_property_types.py +++ b/tools/aws/regen_cfn_property_types.py @@ -52,7 +52,8 @@ FETCH_TIMEOUT_SECONDS = 60 # The resource types whose provisioners read their properties through CfnPropertyTypes. RESOURCE_TYPES = ["AWS::AutoScaling::LaunchConfiguration", "AWS::DSQL::Cluster", "AWS::EC2::Instance", "AWS::EC2::LaunchTemplate", "AWS::ECS::TaskDefinition", "AWS::Events::Rule", - "AWS::Lambda::Function", "AWS::Lambda::LayerVersion"] + "AWS::Lambda::Function", "AWS::Lambda::LayerVersion", + "AWS::SES::ConfigurationSetEventDestination"] # The shared shape each scalar body is written as, inline; a definition keeps its own name. SCALAR_SHAPES = {"string": "String", "integer": "Integer", "boolean": "Boolean", "double": "Double", "json": "Json"} @@ -75,12 +76,21 @@ ANCHORS = { ("AWS::ECS::TaskDefinition/ContainerDefinition", "Memory"): "Integer", ("AWS::ECS::TaskDefinition/ContainerDefinition", "Essential"): "Boolean", ("AWS::ECS::TaskDefinition/KernelCapabilities", "Add"): ["String"], + ("AWS::SES::ConfigurationSetEventDestination/EventDestination", "Enabled"): "Boolean", + ("AWS::SES::ConfigurationSetEventDestination/EventDestination", "MatchingEventTypes"): ["String"], } # Required members the provisioners rely on, measured the same way: shape -> its required members. REQUIRED_ANCHORS = { "AWS::ECS::TaskDefinition/ContainerDefinition": ["Name", "Image"], "AWS::ECS::TaskDefinition/Tmpfs": ["Size"], + "AWS::SES::ConfigurationSetEventDestination": ["ConfigurationSetName", "EventDestination"], + "AWS::SES::ConfigurationSetEventDestination/EventDestination": ["MatchingEventTypes"], + "AWS::SES::ConfigurationSetEventDestination/SnsDestination": ["TopicARN"], + "AWS::SES::ConfigurationSetEventDestination/KinesisFirehoseDestination": ["IAMRoleARN", "DeliveryStreamARN"], + "AWS::SES::ConfigurationSetEventDestination/EventBridgeDestination": ["EventBusArn"], + "AWS::SES::ConfigurationSetEventDestination/DimensionConfiguration": [ + "DimensionValueSource", "DefaultDimensionValue", "DimensionName"], } diff --git a/tools/aws/test_regen_cfn_create_only.py b/tools/aws/test_regen_cfn_create_only.py index 625f14d00c..09f137c10a 100644 --- a/tools/aws/test_regen_cfn_create_only.py +++ b/tools/aws/test_regen_cfn_create_only.py @@ -25,8 +25,13 @@ WIDGET = { "typeName": "AWS::Test::Widget", "properties": {"Name": {"type": "string"}}, "createOnlyProperties": ["/properties/Name", "/properties/Network/Subnet/Id", "/properties/Zone"], + "conditionalCreateOnlyProperties": ["/properties/Network/Name"], +} +GADGET = { + "typeName": "AWS::Test::Gadget", + "properties": {"Label": {"type": "string"}}, + "conditionalCreateOnlyProperties": ["/properties/Label"], } -GADGET = {"typeName": "AWS::Test::Gadget", "properties": {"Label": {"type": "string"}}} def _setup(tmp_path, monkeypatch, types, schemas, schemaless): @@ -42,6 +47,7 @@ def _setup(tmp_path, monkeypatch, types, schemas, schemaless): def test_paths_lose_the_properties_prefix_nested_paths_stay_and_no_list_means_empty(tmp_path, monkeypatch): + monkeypatch.setattr(r, "CONDITIONAL_REPLACEMENT_TYPES", {"AWS::Test::Widget"}) source, output = _setup(tmp_path, monkeypatch, ["AWS::Test::Gadget", "AWS::Test::Widget", "Custom::Reasoned"], {"AWS::Test::Widget": WIDGET, "AWS::Test::Gadget": GADGET}, @@ -53,6 +59,10 @@ def test_paths_lose_the_properties_prefix_nested_paths_stay_and_no_list_means_em "AWS::Test::Gadget": [], "AWS::Test::Widget": ["Name", "Network/Subnet/Id", "Zone"], } + conditional = output.with_name("conditional-create-only-properties.json") + assert json.loads(conditional.read_text(encoding="utf-8")) == { + "AWS::Test::Widget": ["Network/Name"], + } def test_a_type_without_a_schema_is_refused_unless_it_is_in_the_reasoned_list(tmp_path, monkeypatch, capsys): @@ -80,3 +90,15 @@ def test_verify_fails_on_a_hand_edited_entry(tmp_path, monkeypatch): output.write_text(json.dumps(edited, indent=2, sort_keys=True) + "\n", encoding="utf-8") assert r.main(["--verify", "--source-dir", str(source), "--output", str(output)]) == 1 + + +def test_verify_fails_on_a_hand_edited_conditional_entry(tmp_path, monkeypatch): + monkeypatch.setattr(r, "CONDITIONAL_REPLACEMENT_TYPES", {"AWS::Test::Widget"}) + source, output = _setup(tmp_path, monkeypatch, ["AWS::Test::Widget"], {"AWS::Test::Widget": WIDGET}, {}) + assert r.main(["--source-dir", str(source), "--output", str(output)]) == 0 + + conditional = output.with_name("conditional-create-only-properties.json") + assert r.main(["--verify", "--source-dir", str(source), "--output", str(output)]) == 0 + conditional.write_text(json.dumps({"AWS::Test::Widget": []}, indent=2) + "\n", encoding="utf-8") + + assert r.main(["--verify", "--source-dir", str(source), "--output", str(output)]) == 1 diff --git a/tools/aws/test_regen_cfn_property_types.py b/tools/aws/test_regen_cfn_property_types.py index 29e444eb83..599eaa317d 100644 --- a/tools/aws/test_regen_cfn_property_types.py +++ b/tools/aws/test_regen_cfn_property_types.py @@ -68,6 +68,21 @@ def test_the_vendored_file_is_well_formed(): assert r.validate(json.loads(r.OUTPUT.read_text(encoding="utf-8"))) == [] +def test_ses_event_destination_shape_preserves_nested_schema_constraints(): + doc = json.loads(r.OUTPUT.read_text(encoding="utf-8")) + type_name = "AWS::SES::ConfigurationSetEventDestination" + assert doc["operations"][type_name] == type_name + + shapes = doc["shapes"] + assert shapes[type_name]["required"] == ["ConfigurationSetName", "EventDestination"] + destination = shapes[f"{type_name}/EventDestination"] + assert destination["required"] == ["MatchingEventTypes"] + assert destination["members"]["Name"] == "String" + assert destination["members"]["MatchingEventTypes"] == f"{type_name}/EventDestination.MatchingEventTypes" + assert shapes[f"{type_name}/SnsDestination"]["required"] == ["TopicARN"] + assert shapes[f"{type_name}/KinesisFirehoseDestination"]["required"] == ["IAMRoleARN", "DeliveryStreamARN"] + + def test_validate_names_a_missing_shape_and_a_broken_anchor(): doc = json.loads(r.OUTPUT.read_text(encoding="utf-8")) doc["shapes"]["AWS::Events::Rule/RetryPolicy"]["members"]["MaximumRetryAttempts"] = "String"