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

+1 -1
View File
@@ -187,7 +187,7 @@ cross-resource references.
| RDS | `DBInstance` (starts a real container), `DBCluster` (starts a real container), `DBSubnetGroup`, `DBParameterGroup`, `DBClusterParameterGroup`, `DBProxy`, `DBProxyTargetGroup` |
| Aurora DSQL | `Cluster` |
| ElastiCache | `CacheCluster` (starts a real container; modifying an existing cluster in place is not supported), `SubnetGroup`, `User` (Tags are ignored), `UserGroup` (Tags are ignored), `ServerlessCache` (GetAtt uses the dotted Endpoint.* and ReaderEndpoint.* form) |
| Redshift | `Cluster` (single-node container; Port and non-dev DBName ignored; ManageMasterPassword unsupported), `ClusterParameterGroup`, `ClusterSubnetGroup`, `ClusterSecurityGroup` (accepted; no EC2-Classic security group model) |
| Redshift | `Cluster` (single-node container; Port and non-dev DBName ignored; ManageMasterPassword unsupported), `ClusterParameterGroup`, `ClusterSubnetGroup`, `ClusterSecurityGroup` (accepted; no EC2-Classic security group model), `EventSubscription` |
| Redshift Serverless | `Namespace` (Managed admin credentials use Secrets Manager; GetAtt uses the dotted Namespace.* form), `Workgroup` (starts a real container; one workgroup per namespace; capacity, VPC and price-performance settings are stored only; snapshot restore properties are ignored; GetAtt uses the dotted Workgroup.* form) |
| EC2 | `VPC` (deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS), `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog`, `PrefixList` (updated in place; an update that changes `AddressFamily`, or `MaxEntries` together with `Entries`, fails) |
| Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` |
+10
View File
@@ -69,6 +69,16 @@ aws --endpoint-url http://localhost:4566 redshift describe-events \
--source-type cluster-parameter-group --source-identifier event-demo
```
### CloudFormation
`AWS::Redshift::EventSubscription` creates a real subscription. `Ref` returns its
name; `Fn::GetAtt` supports `CustomerAwsId`, `CustSubscriptionId`, `Status`,
`SubscriptionCreationTime`, `SourceIdsList` and `EventCategoriesList`, with the last
two returned as lists. Updating filters, enabled state, topic and tags reconciles the
existing subscription; changing `SubscriptionName` replaces it. Removing optional
filters from the template clears them. Stack deletion removes the subscription.
The attributes follow the [CloudFormation resource schema](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-redshift-eventsubscription.html).
## Supported Actions
<!-- floci:actions:start -->
+6
View File
@@ -444,6 +444,12 @@
<version>${aws.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>cloudformation</artifactId>
<version>${aws.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>ssm</artifactId>
@@ -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) {
@@ -97,6 +97,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.Organizat
import io.github.hectorvent.floci.services.cloudformation.provisioners.PipesCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.RdsCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.RedshiftClusterCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.RedshiftEventSubscriptionCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.RedshiftServerlessCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.Route53CfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.S3CfnProvisioner;
@@ -505,6 +506,7 @@ final class CfnProvisionerFixture {
}
if (redshiftService != null) {
discovered.add(new RedshiftClusterCfnProvisioner(redshiftService));
discovered.add(new RedshiftEventSubscriptionCfnProvisioner(redshiftService));
}
if (redshiftServerlessService != null) {
discovered.add(new RedshiftServerlessCfnProvisioner(redshiftServerlessService));
@@ -39,6 +39,21 @@ class CloudFormationTemplateEngineTest {
(Function<String, String>) name -> null);
}
@Test
void joinAndSelectConsumeTypedGetAttArraysWithoutSplittingMemberCommas() {
CloudFormationTemplateEngine engine = new CloudFormationTemplateEngine("000000000000", "us-east-1", "my-stack",
"stack/id", Map.of(), Map.of(), Map.of("Watcher", Map.of("SourceIdsList", "stored")),
Map.of(), Map.of(), mapper, null, UnaryOperator.identity(), null, Map.of(),
(logicalId, attribute, value) -> mapper.createArrayNode().add("first,with-comma").add("second"));
assertEquals("first,with-comma|second", engine.resolve(json("""
{"Fn::Join":["|",{"Fn::GetAtt":["Watcher","SourceIdsList"]}]}
""")));
assertEquals("first,with-comma", engine.resolve(json("""
{"Fn::Select":[0,{"Fn::GetAtt":["Watcher","SourceIdsList"]}]}
""")));
}
@Test
void getAttOnAMissingAttributeOfAStubbedDisabledServiceIsRefused() {
CloudFormationTemplateEngine e = engineWithAttributes(Map.of("Repo", Map.of(
@@ -0,0 +1,208 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import software.amazon.awssdk.services.cloudformation.model.Output;
import software.amazon.awssdk.services.redshift.RedshiftClient;
import software.amazon.awssdk.services.redshift.model.EventSubscription;
import software.amazon.awssdk.services.redshift.model.RedshiftException;
import java.net.URI;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
@QuarkusTest
class RedshiftEventSubscriptionCfnIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261026/us-east-1/cloudformation/aws4_request";
@TestHTTPResource
URI endpoint;
@ParameterizedTest
@ValueSource(strings = {"CommaDelimitedList", "List<String>"})
void listParametersPopulateSubscriptionFilters(String parameterType) {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String stack = "redshift-list-parameters-" + suffix;
String name = "redshift-list-watcher-" + suffix;
String group = "redshift-list-group-" + suffix;
String body = template(name, true, true)
.replace("\"Resources\": {", """
"Parameters": {
"Categories": {"Type":"%s"},
"Sources": {"Type":"%s"}
},
"Resources": {
""".formatted(parameterType, parameterType))
.replace("\"SourceType\":\"cluster\"",
"\"SourceType\":\"cluster-parameter-group\",\"SourceIds\":{\"Ref\":\"Sources\"}")
.replace("\"EventCategories\":[\"management\"]", "\"EventCategories\":{\"Ref\":\"Categories\"}");
StaticCredentialsProvider credentials = StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"));
try (CloudFormationClient cfn = CloudFormationClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(credentials).build();
RedshiftClient redshift = RedshiftClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(credentials).build()) {
redshift.createClusterParameterGroup(request -> request.parameterGroupName(group)
.parameterGroupFamily("redshift-1.0").description("list parameter source"));
try {
cfn.createStack(request -> request.stackName(stack).templateBody(body).parameters(
parameter -> parameter.parameterKey("Categories").parameterValue("configuration,management"),
parameter -> parameter.parameterKey("Sources").parameterValue(group)));
try {
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, AUTH).status());
EventSubscription created = subscription(redshift, name);
assertEquals(List.of("configuration", "management"), created.eventCategoriesList());
assertEquals(List.of(group), created.sourceIdsList());
} finally {
cfn.deleteStack(request -> request.stackName(stack));
CfnStackWaits.awaitStackDeleted(stack);
}
} finally {
redshift.deleteClusterParameterGroup(request -> request.parameterGroupName(group));
}
}
}
@Test
void rollbackRestoresSubscriptionWhoseSourceWasDeletedAfterCreation() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String stack = "redshift-events-rollback-" + suffix;
String name = "redshift-rollback-watcher-" + suffix;
String group = "redshift-rollback-group-" + suffix;
StaticCredentialsProvider credentials = StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"));
try (CloudFormationClient cfn = CloudFormationClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(credentials).build();
RedshiftClient redshift = RedshiftClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(credentials).build()) {
redshift.createClusterParameterGroup(request -> request.parameterGroupName(group)
.parameterGroupFamily("redshift-1.0").description("rollback source"));
String initial = template(name, true, true).replace("\"SourceType\":\"cluster\"",
"\"SourceType\":\"cluster-parameter-group\",\"SourceIds\":[\"" + group + "\"]")
.replace("\"EventCategories\":[\"management\"]", "\"EventCategories\":[\"configuration\"]");
cfn.createStack(request -> request.stackName(stack).templateBody(initial));
try {
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, AUTH).status());
EventSubscription prior = subscription(redshift, name);
redshift.deleteClusterParameterGroup(request -> request.parameterGroupName(group));
String failingUpdate = template(name, false, false).replace("\"Resources\": {", """
"Resources": {
"Broken": {
"Type":"AWS::SQS::Queue", "DependsOn":"Watcher",
"Properties":{"QueueName":"invalid-fifo","FifoQueue":true}
},
""");
cfn.updateStack(request -> request.stackName(stack).templateBody(failingUpdate));
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack, AUTH).status());
EventSubscription restored = subscription(redshift, name);
assertEquals(prior.sourceIdsList(), restored.sourceIdsList());
assertEquals(prior.sourceType(), restored.sourceType());
assertEquals(prior.eventCategoriesList(), restored.eventCategoriesList());
assertEquals(prior.severity(), restored.severity());
assertEquals(prior.enabled(), restored.enabled());
assertEquals(prior.tags(), restored.tags());
assertEquals(prior.status(), restored.status());
assertEquals(prior.subscriptionCreationTime(), restored.subscriptionCreationTime());
} finally {
cfn.deleteStack(request -> request.stackName(stack));
CfnStackWaits.awaitStackDeleted(stack);
}
}
}
@Test
void stackCreatesUpdatesReplacesAndDeletesSubscriptionWithExactGetAttValues() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String stack = "redshift-events-cfn-" + suffix;
String name = "redshift-watcher-" + suffix;
String replacement = "redshift-renamed-" + suffix;
StaticCredentialsProvider credentials = StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"));
try (CloudFormationClient cfn = CloudFormationClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(credentials).build();
RedshiftClient redshift = RedshiftClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(credentials).build()) {
cfn.createStack(request -> request.stackName(stack).templateBody(template(name, true, true)));
try {
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, AUTH).status());
EventSubscription created = subscription(redshift, name);
Map<String, String> outputs = cfn.describeStacks(request -> request.stackName(stack)).stacks().getFirst()
.outputs().stream().collect(Collectors.toMap(Output::outputKey, Output::outputValue));
assertEquals(name, outputs.get("Ref"));
assertEquals(name, outputs.get("CustSubscriptionId"));
assertEquals(created.customerAwsId(), outputs.get("CustomerAwsId"));
assertEquals("active", outputs.get("Status"));
assertEquals(created.subscriptionCreationTime(), Instant.parse(outputs.get("SubscriptionCreationTime")));
assertEquals("", outputs.get("SourceIdsList"));
assertEquals("management", outputs.get("EventCategoriesList"));
assertEquals("initial", created.tags().getFirst().value());
cfn.updateStack(request -> request.stackName(stack).templateBody(template(name, false, false)));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, AUTH).status());
EventSubscription updated = subscription(redshift, name);
assertFalse(updated.enabled());
assertNull(updated.sourceType());
assertNull(updated.severity());
assertTrue(updated.eventCategoriesList().isEmpty());
assertTrue(updated.tags().isEmpty());
assertEquals(created.subscriptionCreationTime(), updated.subscriptionCreationTime());
cfn.updateStack(request -> request.stackName(stack).templateBody(template(replacement, true, true)));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, AUTH).status());
assertEquals(replacement, subscription(redshift, replacement).custSubscriptionId());
assertThrows(RedshiftException.class, () -> subscription(redshift, name));
} finally {
cfn.deleteStack(request -> request.stackName(stack));
CfnStackWaits.awaitStackDeleted(stack);
}
assertThrows(RedshiftException.class, () -> subscription(redshift, replacement));
}
}
private static EventSubscription subscription(RedshiftClient redshift, String name) {
return redshift.describeEventSubscriptions(request -> request.subscriptionName(name)).eventSubscriptionsList().getFirst();
}
private static String template(String name, boolean enabled, boolean filtered) {
String filters = filtered ? """
,"SourceType":"cluster","Severity":"INFO","EventCategories":["management"],
"Tags":[{"Key":"phase","Value":"initial"}]
""" : "";
return """
{
"Resources": {
"Topic": {"Type":"AWS::SNS::Topic"},
"Watcher": {
"Type":"AWS::Redshift::EventSubscription",
"Properties": {
"SubscriptionName":"%s", "SnsTopicArn":{"Ref":"Topic"}, "Enabled":%s%s
}
}
},
"Outputs": {
"Ref":{"Value":{"Ref":"Watcher"}},
"CustomerAwsId":{"Value":{"Fn::GetAtt":["Watcher","CustomerAwsId"]}},
"CustSubscriptionId":{"Value":{"Fn::GetAtt":["Watcher","CustSubscriptionId"]}},
"Status":{"Value":{"Fn::GetAtt":["Watcher","Status"]}},
"SubscriptionCreationTime":{"Value":{"Fn::GetAtt":["Watcher","SubscriptionCreationTime"]}},
"SourceIdsList":{"Value":{"Fn::Join":[",",{"Fn::GetAtt":["Watcher","SourceIdsList"]}]}},
"EventCategoriesList":{"Value":{"Fn::Join":[",",{"Fn::GetAtt":["Watcher","EventCategoriesList"]}]}}
}
}
""".formatted(name, enabled, filters);
}
}
@@ -0,0 +1,195 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
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 org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class RedshiftEventSubscriptionCfnProvisionerTest {
private static final String TYPE = "AWS::Redshift::EventSubscription";
private static final String TOPIC = "arn:aws:sns:us-east-1:000000000000:events";
private final ObjectMapper mapper = new ObjectMapper();
private final RedshiftService redshift = mock(RedshiftService.class);
private final RedshiftEventSubscriptionCfnProvisioner provisioner =
new RedshiftEventSubscriptionCfnProvisioner(redshift);
@Test
void createSetsRefAndEverySchemaAttribute() throws Exception {
EventSubscription subscription = subscription("watcher");
when(redshift.createEventSubscription(eq("watcher"), eq(TOPIC), eq("cluster"), eq(List.of("warehouse")),
eq(List.of("management")), eq("INFO"), eq(true), eq(Map.of("team", "analytics"))))
.thenReturn(subscription);
ObjectNode props = properties("watcher");
props.put("SourceType", "cluster").put("Severity", "INFO").put("Enabled", true);
props.putArray("SourceIds").add("warehouse");
props.putArray("EventCategories").add("management");
props.putArray("Tags").addObject().put("Key", "team").put("Value", "analytics");
StackResource resource = resource();
provisioner.provision(resource, props, context(null));
assertEquals("watcher", resource.getPhysicalId());
assertEquals(Set.of("CustomerAwsId", "CustSubscriptionId", "Status", "SubscriptionCreationTime",
"SourceIdsList", "EventCategoriesList"), resource.getAttributes().keySet());
assertEquals("000000000000", resource.getAttributes().get("CustomerAwsId"));
assertEquals("watcher", resource.getAttributes().get("CustSubscriptionId"));
assertEquals("active", resource.getAttributes().get("Status"));
assertEquals("2026-10-26T12:00:00Z", resource.getAttributes().get("SubscriptionCreationTime"));
assertEquals(mapper.readTree("[\"warehouse\"]"), provisioner.attributeValue(TYPE, "SourceIdsList",
resource.getAttributes().get("SourceIdsList")));
assertEquals(mapper.readTree("[\"management\"]"), provisioner.attributeValue(TYPE, "EventCategoriesList",
resource.getAttributes().get("EventCategoriesList")));
}
@Test
void updateKeepsPhysicalIdAndReconcilesTags() {
when(redshift.describeEventSubscriptions("watcher", null, null, null, null))
.thenReturn(new PaginatedResult<>(List.of(subscription("watcher")), null));
when(redshift.reconcileEventSubscription(eq("watcher"), eq(TOPIC), any(), any(), any(), any(), eq(false), any()))
.thenReturn(subscription("watcher"));
ObjectNode props = properties("watcher").put("Enabled", false);
StackResource resource = resource();
resource.setPhysicalId("watcher");
provisioner.provision(resource, props, context("watcher"));
assertEquals("watcher", resource.getPhysicalId());
verify(redshift, never()).createEventSubscription(any(), any(), any(), any(), any(), any(), any(), any());
verify(redshift).reconcileEventSubscription("watcher", TOPIC, null, List.of(), List.of(), null, false, Map.of());
}
@Test
void inPlaceRollbackRestoresFiltersTagsAndSavedAttributes() {
EventSubscription prior = subscription("watcher");
prior.setSnsTopicArn(TOPIC);
prior.setSourceType("cluster");
prior.setSeverity("INFO");
prior.setEnabled(true);
prior.setTags(Map.of("phase", "prior"));
prior.setStatus("topic-not-exist");
when(redshift.describeEventSubscriptions("watcher", null, null, null, null))
.thenReturn(new PaginatedResult<>(List.of(prior), null));
EventSubscription updated = subscription("watcher");
updated.setSourceIdsList(List.of("replacement"));
updated.setEventCategoriesList(List.of("configuration"));
when(redshift.reconcileEventSubscription(eq("watcher"), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(updated);
StackResource resource = resource();
resource.setPhysicalId("watcher");
Map<String, String> priorAttributes = Map.of(
"CustomerAwsId", "000000000000", "CustSubscriptionId", "watcher", "Status", "topic-not-exist",
"SubscriptionCreationTime", "2026-10-26T12:00:00Z", "SourceIdsList", "[\"warehouse\"]",
"EventCategoriesList", "[\"management\"]", CfnRollback.USES_ATTR_PREFIX + "Test", "retained");
resource.getAttributes().putAll(priorAttributes);
provisioner.provision(resource, properties("watcher").put("Enabled", false), context("watcher"));
assertEquals("active", resource.getAttributes().get("Status"));
assertEquals("[\"replacement\"]", resource.getAttributes().get("SourceIdsList"));
assertEquals("[\"configuration\"]", resource.getAttributes().get("EventCategoriesList"));
assertTrue(provisioner.rollbackUpdate(resource));
assertEquals(priorAttributes, resource.getAttributes());
verify(redshift).restoreEventSubscription("watcher", TOPIC, "cluster", List.of("warehouse"),
List.of("management"), "INFO", true, Map.of("phase", "prior"), "topic-not-exist");
}
@Test
void changedNameCreatesReplacementAndDeletesPriorAfterCommit() {
when(redshift.createEventSubscription(eq("replacement"), eq(TOPIC), any(), any(), any(), any(), any(), any()))
.thenReturn(subscription("replacement"));
StackResource resource = resource();
resource.setPhysicalId("watcher");
resource.getAttributes().put("CustSubscriptionId", "watcher");
provisioner.provision(resource, properties("replacement"), context("watcher"));
assertEquals("replacement", resource.getPhysicalId());
assertTrue(provisioner.hasReplacementUpdate(resource));
verify(redshift, never()).deleteEventSubscription(any());
provisioner.completeUpdate(resource);
verify(redshift).deleteEventSubscription("watcher");
}
@Test
void replacementRollbackDeletesNewSubscriptionAndRestoresPriorIdentity() {
when(redshift.createEventSubscription(eq("replacement"), eq(TOPIC), any(), any(), any(), any(), any(), any()))
.thenReturn(subscription("replacement"));
StackResource resource = resource();
resource.setPhysicalId("watcher");
resource.getAttributes().put("CustSubscriptionId", "watcher");
provisioner.provision(resource, properties("replacement"), context("watcher"));
assertTrue(provisioner.rollbackUpdate(resource));
assertEquals("watcher", resource.getPhysicalId());
verify(redshift).deleteEventSubscription("replacement");
}
@Test
void deleteToleratesOnlyMissingSubscription() {
doThrow(new AwsException("SubscriptionNotFound", "gone", 404)).when(redshift).deleteEventSubscription("gone");
assertDoesNotThrow(() -> provisioner.delete(TYPE, "gone", "us-east-1"));
doThrow(new AwsException("SNSNoAuthorization", "denied", 400)).when(redshift).deleteEventSubscription("denied");
assertThrows(AwsException.class, () -> provisioner.delete(TYPE, "denied", "us-east-1"));
}
@Test
void missingRequiredNameFailsBeforeCallingService() {
assertThrows(AwsException.class, () -> provisioner.provision(resource(), mapper.createObjectNode(), context(null)));
verifyNoInteractions(redshift);
}
private ObjectNode properties(String name) {
return mapper.createObjectNode().put("SubscriptionName", name).put("SnsTopicArn", TOPIC);
}
private StackResource resource() {
StackResource resource = new StackResource();
resource.setLogicalId("Watcher");
resource.setResourceType(TYPE);
resource.setAttributes(new HashMap<>());
return resource;
}
private ProvisionContext context(String prior) {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(invocation -> invocation.getArgument(0, JsonNode.class).asText());
when(engine.resolveNode(any())).thenAnswer(invocation -> invocation.getArgument(0));
when(engine.resolveStringList(any())).thenAnswer(invocation -> {
List<String> values = new ArrayList<>();
JsonNode array = invocation.getArgument(0);
array.forEach(value -> values.add(value.asText()));
return values;
});
return new ProvisionContext(engine, "us-east-1", "000000000000", "event-stack", prior);
}
private EventSubscription subscription(String name) {
EventSubscription subscription = new EventSubscription();
subscription.setCustSubscriptionId(name);
subscription.setCustomerAwsId("000000000000");
subscription.setStatus("active");
subscription.setSubscriptionCreationTime(Instant.parse("2026-10-26T12:00:00Z"));
subscription.setSourceIdsList(List.of("warehouse"));
subscription.setEventCategoriesList(List.of("management"));
return subscription;
}
}
@@ -19,6 +19,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import java.time.Clock;
@@ -33,6 +34,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiPredicate;
@@ -66,6 +68,44 @@ class RedshiftEventServiceTest {
private RedshiftEventService service;
private StorageFactory factory;
@ParameterizedTest
@ValueSource(booleans = {false, true})
void tagRequestsApplyToTheLatestCloudFormationTags(boolean delete) throws Exception {
create("watcher", null, List.of(), List.of(), null);
service.replaceSubscriptionTags("watcher", Map.of("phase", "initial", "remove", "initial"));
RedshiftService redshift = new RedshiftService(factory, null, null,
new RegionResolver("us-east-1", "000000000000"), null, null, null, null,
objectMapper, null, null, service);
String arn = "arn:aws:redshift:us-east-1:000000000000:eventsubscription:watcher";
CountDownLatch started = new CountDownLatch(1);
AtomicReference<Thread> taggingThread = new AtomicReference<>();
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
Future<?> tagging;
synchronized (service) {
tagging = executor.submit(() -> {
taggingThread.set(Thread.currentThread());
started.countDown();
if (delete) {
redshift.deleteTags(arn, List.of("remove"));
} else {
redshift.createTags(arn, Map.of("api", "added"));
}
});
assertTrue(started.await(5, TimeUnit.SECONDS));
assertThrows(TimeoutException.class, () -> tagging.get(300, TimeUnit.MILLISECONDS));
assertEquals(Thread.State.BLOCKED, taggingThread.get().getState());
redshift.reconcileEventSubscription("watcher", TOPIC, null, List.of(), List.of(), null, true,
Map.of("phase", "updated", "remove", "updated"));
}
tagging.get(5, TimeUnit.SECONDS);
}
Map<String, String> expected = delete ? Map.of("phase", "updated")
: Map.of("phase", "updated", "remove", "updated", "api", "added");
assertEquals(expected, redshift.listTagsForResource(arn));
}
@ParameterizedTest
@CsvSource({"success,active", "NotFound,topic-not-exist", "AuthorizationError,no-permission"})
void explicitRecordingUsesTheOwnersHistorySubscriptionsAndFailureStatus(String failure, String expectedStatus) {
@@ -160,6 +160,7 @@ AWS::Redshift::Cluster RedshiftClusterCfnProvisioner
AWS::Redshift::ClusterParameterGroup RedshiftClusterCfnProvisioner
AWS::Redshift::ClusterSecurityGroup RedshiftClusterCfnProvisioner
AWS::Redshift::ClusterSubnetGroup RedshiftClusterCfnProvisioner
AWS::Redshift::EventSubscription RedshiftEventSubscriptionCfnProvisioner
AWS::RedshiftServerless::Namespace RedshiftServerlessCfnProvisioner
AWS::RedshiftServerless::Workgroup RedshiftServerlessCfnProvisioner
AWS::Route53::HealthCheck Route53CfnProvisioner
1 AWS::ApiGateway::Account ApiGatewayAccountCfnProvisioner
160 AWS::Redshift::ClusterParameterGroup RedshiftClusterCfnProvisioner
161 AWS::Redshift::ClusterSecurityGroup RedshiftClusterCfnProvisioner
162 AWS::Redshift::ClusterSubnetGroup RedshiftClusterCfnProvisioner
163 AWS::Redshift::EventSubscription RedshiftEventSubscriptionCfnProvisioner
164 AWS::RedshiftServerless::Namespace RedshiftServerlessCfnProvisioner
165 AWS::RedshiftServerless::Workgroup RedshiftServerlessCfnProvisioner
166 AWS::Route53::HealthCheck Route53CfnProvisioner
+1 -1
View File
@@ -95,7 +95,7 @@ type_order:
AWS::ElastiCache:
[CacheCluster, SubnetGroup, User, UserGroup, ServerlessCache]
AWS::Redshift:
[Cluster, ClusterParameterGroup, ClusterSubnetGroup, ClusterSecurityGroup]
[Cluster, ClusterParameterGroup, ClusterSubnetGroup, ClusterSecurityGroup, EventSubscription]
AWS::RedshiftServerless:
[Namespace, Workgroup]
AWS::EC2: