feat(cloudformation): provision Redshift event subscriptions (#6664)

* feat(redshift): support event history and SNS notifications

* fix(redshift): guard stale delivery failures and prune all event scopes

* feat(cloudformation): provision Redshift event subscriptions

* fix(redshift): scope snapshot events and serialize subscription tag mutations

* feat(cloudformation): provision Redshift event subscriptions

* fix(cloudformation): resolve Redshift subscription list parameters

Use the shared list reader for SourceIds and EventCategories. Cover CommaDelimitedList and List<String> parameters through the AWS SDK and verify concurrent tag requests preserve CloudFormation tag updates.

* fix(redshift): honor event disablement and restore rollback attributes

Check the EventBridge external service key before publishing API events. Snapshot and restore CloudFormation resource attributes alongside subscription state during in-place rollback.

* fix(redshift): drop API event publisher and share subscription setup

Remove RedshiftApiEventPublisher, its handler hook, tests and docs, which are not part of the CloudFormation resource and emit CloudTrail-style events without a trail. Route createSubscription and replaceSubscription through one helper that normalizes the subscription fields.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-27 23:28:52 -04:00
1 parent 5c20d54646
commit d3c4732b31
14 files changed
+733 -11

No files matched your search

@@ -563,7 +563,7 @@ public class CloudFormationTemplateEngine {
requireStringAttribute(join.get(1),
"Template error: every Fn::Join object requires two parameters, (1) a string delimiter"
+ " and (2) a list of strings to be joined or a function that returns a list"
+ " of strings (such as Fn::GetAZs) to be joined.");
+ " of strings (such as Fn::GetAZs) to be joined.", true);
// CDK splices a dynamic reference across fragments, for example
// ["{{resolve:secretsmanager:", {"Ref": "Secret"}, ":SecretString:password::}}"], so the
// fragments are only intrinsic-resolved here and the caller resolves dynamic references on
@@ -572,14 +572,26 @@ public class CloudFormationTemplateEngine {
}
private void requireStringAttribute(JsonNode node, String message) {
requireStringAttribute(node, message, false);
}
private void requireStringAttribute(JsonNode node, String message, boolean listSource) {
if (node == null) {
return;
}
if (node.has("Fn::GetAtt") && !isStringAttribute(node.get("Fn::GetAtt"))) {
throw new AwsException("ValidationError", message, 400);
JsonNode value = resolveGetAttNode(node.get("Fn::GetAtt"));
if (!listSource || !value.isArray()) {
throw new AwsException("ValidationError", message, 400);
}
for (JsonNode member : value) {
if (!member.isTextual()) {
throw new AwsException("ValidationError", message, 400);
}
}
}
if (node.has("Fn::If")) {
requireStringAttribute(selectIfBranch(node.get("Fn::If")), message);
requireStringAttribute(selectIfBranch(node.get("Fn::If")), message, listSource);
} else if (node.has("Fn::Select")) {
requireStringAttribute(selectedElement(node.get("Fn::Select")), message);
} else if (node.isArray()) {
@@ -651,6 +663,13 @@ public class CloudFormationTemplateEngine {
return resolveListElements(node, resolveDynamicReferences);
}
if (node.isObject()) {
if (node.has("Fn::GetAtt")) {
JsonNode attribute = resolveGetAttNode(node.get("Fn::GetAtt"));
if (attribute.isArray()) {
attribute.forEach(member -> out.add(member.asText()));
return out;
}
}
if (node.has("Fn::If")) {
// Fn::If's branch can itself be any of the shapes this method already handles
// (literal array, Fn::Split, ...), so recurse into it rather than falling through
@@ -0,0 +1,165 @@
package io.github.hectorvent.floci.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;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
import io.github.hectorvent.floci.services.redshift.model.EventSubscription;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@ApplicationScoped
public class RedshiftEventSubscriptionCfnProvisioner implements CfnResourceProvisioner {
private static final String TYPE = "AWS::Redshift::EventSubscription";
private static final String UPDATE_SNAPSHOT = CfnRollback.USES_ATTR_PREFIX + "RedshiftEventSubscriptionUpdate";
private static final ObjectMapper MAPPER = new ObjectMapper();
private final RedshiftService redshift;
@Inject
public RedshiftEventSubscriptionCfnProvisioner(RedshiftService redshift) {
this.redshift = redshift;
}
@Override
public Set<String> resourceTypes() {
return Set.of(TYPE);
}
@Override
public void provision(StackResource resource, JsonNode props, ProvisionContext ctx) {
String name = ctx.resolveOptional(props, "SubscriptionName");
if (name == null || name.isBlank()) {
throw new AwsException("ValidationError", "SubscriptionName is required.", 400);
}
String topic = ctx.resolveOptional(props, "SnsTopicArn");
String type = ctx.resolveOptional(props, "SourceType");
List<String> ids = ctx.resolveStringList(props, "SourceIds");
List<String> categories = ctx.resolveStringList(props, "EventCategories");
String severity = ctx.resolveOptional(props, "Severity");
String enabledValue = ctx.resolveOptional(props, "Enabled");
Boolean enabled = enabledValue == null ? true : Boolean.valueOf(enabledValue);
Map<String, String> tags = ctx.resolveTags(props, "Tags");
Map<String, String> attributesBefore = Map.copyOf(resource.getAttributes());
if (ctx.reusesPriorEntity(name)) {
EventSubscription prior = redshift.describeEventSubscriptions(name, null, null, null, null).items().getFirst();
resource.getAttributes().put(UPDATE_SNAPSHOT, snapshot(prior, attributesBefore).toString());
}
EventSubscription subscription = ctx.reusesPriorEntity(name)
? redshift.reconcileEventSubscription(name, topic, type, ids, categories, severity, enabled, tags)
: redshift.createEventSubscription(name, topic, type, ids, categories, severity, enabled, tags);
resource.setPhysicalId(subscription.getCustSubscriptionId());
resource.getAttributes().put("CustomerAwsId", subscription.getCustomerAwsId());
resource.getAttributes().put("CustSubscriptionId", subscription.getCustSubscriptionId());
resource.getAttributes().put("Status", subscription.getStatus());
resource.getAttributes().put("SubscriptionCreationTime", subscription.getSubscriptionCreationTime().toString());
resource.getAttributes().put("SourceIdsList", array(subscription.getSourceIdsList()).toString());
resource.getAttributes().put("EventCategoriesList", array(subscription.getEventCategoriesList()).toString());
if (ctx.isUpdate()) {
ReplacementCleanup.record(resource, ctx, attributesBefore);
}
}
@Override
public JsonNode attributeValue(String resourceType, String attributeName, String value) {
if ("SourceIdsList".equals(attributeName) || "EventCategoriesList".equals(attributeName)) {
try {
return MAPPER.readTree(value);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Invalid stored Redshift event subscription attribute " + attributeName, e);
}
}
return CfnResourceProvisioner.super.attributeValue(resourceType, attributeName, value);
}
@Override
public void delete(String resourceType, String physicalId, String region) {
CfnDeletes.safeDelete("Redshift event subscription", physicalId,
() -> redshift.deleteEventSubscription(physicalId), "SubscriptionNotFound");
}
@Override
public boolean hasReplacementUpdate(StackResource resource) {
return ReplacementCleanup.hasReplacement(resource);
}
@Override
public String updateCleanupPhysicalId(StackResource resource) {
return ReplacementCleanup.cleanupPhysicalId(resource);
}
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
return ReplacementCleanup.complete(resource, this::delete);
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(UPDATE_SNAPSHOT);
ReplacementCleanup.clear(resource);
}
@Override
public boolean rollbackUpdate(StackResource resource) {
if (ReplacementCleanup.rollback(resource, this::delete)) {
return true;
}
String raw = resource.getAttributes().get(UPDATE_SNAPSHOT);
if (raw == null) {
return false;
}
try {
JsonNode snapshot = MAPPER.readTree(raw);
Map<String, String> tags = new LinkedHashMap<>();
snapshot.path("tags").fields().forEachRemaining(entry -> tags.put(entry.getKey(), entry.getValue().asText()));
redshift.restoreEventSubscription(resource.getPhysicalId(), snapshot.path("topic").asText(),
snapshot.path("type").asText(null), readStrings(snapshot.path("ids")),
readStrings(snapshot.path("categories")), snapshot.path("severity").asText(null),
snapshot.path("enabled").asBoolean(), tags, snapshot.path("status").asText());
resource.getAttributes().clear();
snapshot.path("attributes").fields().forEachRemaining(entry ->
resource.getAttributes().put(entry.getKey(), entry.getValue().asText()));
return true;
} catch (JsonProcessingException e) {
throw new IllegalStateException("Invalid Redshift event subscription update snapshot", e);
}
}
private static ObjectNode snapshot(EventSubscription subscription, Map<String, String> attributes) {
ObjectNode snapshot = MAPPER.createObjectNode();
snapshot.put("topic", subscription.getSnsTopicArn());
snapshot.put("type", subscription.getSourceType());
snapshot.put("severity", subscription.getSeverity());
snapshot.put("enabled", subscription.isEnabled());
snapshot.put("status", subscription.getStatus());
snapshot.set("ids", array(subscription.getSourceIdsList()));
snapshot.set("categories", array(subscription.getEventCategoriesList()));
ObjectNode tags = snapshot.putObject("tags");
subscription.getTags().forEach(tags::put);
snapshot.set("attributes", MAPPER.valueToTree(attributes));
return snapshot;
}
private static List<String> readStrings(JsonNode array) {
List<String> values = new ArrayList<>();
array.forEach(member -> values.add(member.asText()));
return values;
}
private static ArrayNode array(List<String> values) {
ArrayNode array = MAPPER.createArrayNode();
values.forEach(array::add);
return array;
}
}
@@ -353,12 +353,7 @@ public class RedshiftEventService {
subscription.setSnsTopicArn(snsTopicArn);
subscription.setStatus("active");
subscription.setSubscriptionCreationTime(clock.instant().truncatedTo(ChronoUnit.MILLIS));
subscription.setSourceType(blankToNull(sourceType));
subscription.setSourceIdsList(sourceIds == null ? new ArrayList<>() : new ArrayList<>(sourceIds));
subscription.setEventCategoriesList(categories == null ? new ArrayList<>() : new ArrayList<>(categories));
subscription.setSeverity(blankToNull(severity) == null ? null : severity.toUpperCase(Locale.ROOT));
subscription.setEnabled(enabled == null || enabled);
subscription.setTags(tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(tags));
applyConfiguration(subscription, sourceType, sourceIds, categories, severity, enabled, tags);
subscriptions.put(key(name), subscription);
subscriptions.flush();
return subscription;
@@ -555,6 +550,23 @@ public class RedshiftEventService {
replaceSubscriptionTags(name, updated);
}
public synchronized EventSubscription reconcileSubscription(String name, String snsTopicArn, String sourceType,
List<String> sourceIds, List<String> categories,
String severity, Boolean enabled, Map<String, String> tags,
BiPredicate<String, String> sourceExists) {
return replaceSubscription(name, snsTopicArn, sourceType, sourceIds, categories, severity,
enabled, tags, sourceExists, null);
}
/** Restores trusted CloudFormation state even when its topic or source has since been deleted. */
public synchronized EventSubscription restoreSubscription(String name, String snsTopicArn, String sourceType,
List<String> sourceIds, List<String> categories,
String severity, Boolean enabled, Map<String, String> tags,
String status) {
return replaceSubscription(name, snsTopicArn, sourceType, sourceIds, categories, severity,
enabled, tags, (type, id) -> true, status);
}
public synchronized void replaceSubscriptionTags(String name, Map<String, String> tags) {
EventSubscription subscription = requireSubscription(name);
validateTags(tags);
@@ -563,5 +575,39 @@ public class RedshiftEventService {
subscriptions.flush();
}
private EventSubscription replaceSubscription(String name, String snsTopicArn, String sourceType,
List<String> sourceIds, List<String> categories, String severity,
Boolean enabled, Map<String, String> tags,
BiPredicate<String, String> sourceExists, String restoredStatus) {
EventSubscription prior = requireSubscription(name);
validateTags(tags);
validateFilters(sourceType, sourceIds, categories, severity, (type, id) ->
Objects.equals(type, prior.getSourceType()) && prior.getSourceIdsList().contains(id)
|| sourceExists.test(type, id));
boolean changedTopic = !Objects.equals(snsTopicArn, prior.getSnsTopicArn());
if (restoredStatus == null && changedTopic) {
requireTopic(snsTopicArn);
}
EventSubscription updated = new EventSubscription();
updated.setCustomerAwsId(prior.getCustomerAwsId());
updated.setCustSubscriptionId(name);
updated.setSubscriptionCreationTime(prior.getSubscriptionCreationTime());
updated.setSnsTopicArn(snsTopicArn);
updated.setStatus(restoredStatus != null ? restoredStatus : changedTopic ? "active" : prior.getStatus());
applyConfiguration(updated, sourceType, sourceIds, categories, severity, enabled, tags);
subscriptions.put(key(name), updated);
subscriptions.flush();
return updated;
}
private static void applyConfiguration(EventSubscription subscription, String sourceType,
List<String> sourceIds, List<String> categories, String severity,
Boolean enabled, Map<String, String> tags) {
subscription.setSourceType(blankToNull(sourceType));
subscription.setSourceIdsList(sourceIds == null ? new ArrayList<>() : new ArrayList<>(sourceIds));
subscription.setEventCategoriesList(categories == null ? new ArrayList<>() : new ArrayList<>(categories));
subscription.setSeverity(blankToNull(severity) == null ? null : severity.toUpperCase(Locale.ROOT));
subscription.setEnabled(enabled == null || enabled);
subscription.setTags(tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(tags));
}
}
@@ -1946,6 +1946,21 @@ public class RedshiftService implements ManagedSecretRotator {
eventService().deleteSubscription(name);
}
public EventSubscription reconcileEventSubscription(String name, String snsTopicArn, String sourceType,
List<String> sourceIds, List<String> categories,
String severity, Boolean enabled, Map<String, String> tags) {
return eventService().reconcileSubscription(name, snsTopicArn, sourceType, sourceIds, categories,
severity, enabled, tags, this::eventSourceExists);
}
public EventSubscription restoreEventSubscription(String name, String snsTopicArn, String sourceType,
List<String> sourceIds, List<String> categories,
String severity, Boolean enabled, Map<String, String> tags,
String status) {
return eventService().restoreSubscription(name, snsTopicArn, sourceType, sourceIds, categories,
severity, enabled, tags, status);
}
public PaginatedResult<EventSubscription> describeEventSubscriptions(String name, List<String> tagKeys,
List<String> tagValues, Integer maxRecords,
String marker) {