fix(redshift): keep tags, VPC and subnet detail on cluster subnet groups (#7211)

* fix(redshift): keep tags, VPC and subnet detail on cluster subnet groups

CreateClusterSubnetGroup dropped Tags and passed a null VPC, so
DescribeClusterSubnetGroups returned no Tags, VpcId, SubnetGroupStatus or
SubnetAvailabilityZone and the Terraform provider saw drift on every plan.

Tags are now parsed (Tags.member.N and Tags.Tag.N) and stored on the group,
where DescribeTags/CreateTags already find them under the subnetgroup ARN.
The VPC and each subnet's zone are resolved from EC2 on create and modify;
subnets EC2 does not know are kept unresolved, as before. Groups persisted
earlier load unchanged (the new zone map is nullable).

* fix(redshift): inject Ec2Service through the constructor

Replace the Ec2Service field injection with a constructor parameter held
in a final field. The previous @Inject signature stays as a package-private
delegating constructor passing null, so hand-built test services still
skip subnet resolution.

* test(redshift): build the EC2 setup requests with Ec2Requests

ec2Id now only extracts the id from the response; the auth header and
Action come from the shared Ec2Requests.ec2 helper.

* test(redshift): make ec2Id a plain path extraction

Call sites build the EC2 request with Ec2Requests.ec2 and pass it in;
the account and region are named constants.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-11-02 10:09:50 -04:00
1 parent 3963e03797
commit 4438e3df49
6 files changed
+122 -7

No files matched your search

+1 -1
View File
@@ -938,7 +938,7 @@ These views expose the documented Redshift column names, types, and ordering map
- Real Redshift SQL semantics: the data plane is stock PostgreSQL. Redshift-only table DDL keywords (DISTSTYLE / DISTKEY / SORTKEY / ENCODE) are stripped so CREATE TABLE / ALTER TABLE executes (see [SQL Interceptor](#sql-interceptor)), but the distribution/sort behavior they request is not; SUPER and Spectrum features outside the documented [Phase 1 subset](#redshift-spectrum-phase-1) are not emulated.
- Multi-node clusters: `NodeType` and `NumberOfNodes` are stored as metadata; every cluster is a single PostgreSQL container.
- Parameter groups apply no real engine settings; values are stored and echoed back only.
- Subnet groups, VPC routing, and security groups are metadata only.
- Subnet groups, VPC routing, and security groups are metadata only. A subnet group still records its tags, and takes its VPC and each subnet's availability zone from EC2 when the subnets exist there; subnets EC2 does not know are kept as given.
- Resize, pause/resume, and IAM authentication.
- Cross-account role ARNs are not supported for COPY or UNLOAD.
- The auth proxy validates the master user's password and any live `GetClusterCredentials` credential. Other non-master users pass straight through to PostgreSQL, which remains the authority for their credentials.
@@ -439,7 +439,7 @@ public class RedshiftQueryHandler {
}
String description = params.getFirst("Description");
List<String> subnetIds = memberList(params, "SubnetIds");
ClusterSubnetGroup group = service.createClusterSubnetGroup(name, description, null, subnetIds);
ClusterSubnetGroup group = service.createClusterSubnetGroup(name, description, null, subnetIds, parseTags(params));
String xml = new XmlBuilder()
.start("CreateClusterSubnetGroupResponse")
.start("CreateClusterSubnetGroupResult")
@@ -1367,11 +1367,21 @@ public class RedshiftQueryHandler {
.elem("ClusterSubnetGroupName", group.getClusterSubnetGroupName())
.elem("Description", group.getDescription())
.elem("VpcId", group.getVpcId())
.elem("SubnetGroupStatus", "Complete")
.start("Subnets");
Map<String, String> zones = group.getSubnetZones() == null ? Map.of() : group.getSubnetZones();
for (String subnetId : group.getSubnetIds()) {
builder.start("Subnet").elem("SubnetIdentifier", subnetId).end("Subnet");
builder.start("Subnet").elem("SubnetIdentifier", subnetId);
if (zones.get(subnetId) != null) {
builder.start("SubnetAvailabilityZone").elem("Name", zones.get(subnetId)).end("SubnetAvailabilityZone");
}
builder.elem("SubnetStatus", "Active").end("Subnet");
}
return builder.end("Subnets").end("ClusterSubnetGroup").build();
builder.end("Subnets").start("Tags");
for (Map.Entry<String, String> tag : group.getTags().entrySet()) {
builder.start("Tag").elem("Key", tag.getKey()).elem("Value", tag.getValue()).end("Tag");
}
return builder.end("Tags").end("ClusterSubnetGroup").build();
}
private Response eventSubscriptionResponse(String operation, EventSubscription subscription) {
@@ -13,6 +13,8 @@ import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Subnet;
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
import io.github.hectorvent.floci.services.redshift.RedshiftEventCatalog.EventInfo;
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle;
@@ -108,6 +110,7 @@ public class RedshiftService implements ManagedSecretRotator {
private final RedshiftAuditLogPublisher auditLogPublisher;
private final RedshiftEventService events;
private final RedshiftIntegrationEventPublisher integrationEvents;
private final Ec2Service ec2Service;
// Proxy ports currently handed out, so allocateProxyPort never double-assigns within this JVM.
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
private final ConcurrentHashMap<ResourceKey, ResourceLock> resourceLocks = new ConcurrentHashMap<>();
@@ -190,7 +193,8 @@ public class RedshiftService implements ManagedSecretRotator {
RedshiftCredentialBroker credentialBroker,
SecretsManagerService secretsManagerService, ObjectMapper objectMapper,
DynamoDbStreamReader streamReader, RedshiftAuditLogPublisher auditLogPublisher,
RedshiftEventService events, RedshiftIntegrationEventPublisher integrationEvents) {
RedshiftEventService events, RedshiftIntegrationEventPublisher integrationEvents,
Ec2Service ec2Service) {
this.clusters = storageFactory.create("redshift", "redshift-clusters.json", new TypeReference<Map<String, Cluster>>() {});
this.snapshots = storageFactory.create("redshift", "redshift-snapshots.json", new TypeReference<Map<String, Snapshot>>() {});
this.snapshotCopies = storageFactory.create("redshift", "redshift-snapshot-copies.json", new TypeReference<Map<String, Snapshot>>() {});
@@ -213,6 +217,19 @@ public class RedshiftService implements ManagedSecretRotator {
this.auditLogPublisher = auditLogPublisher;
this.events = events;
this.integrationEvents = integrationEvents;
this.ec2Service = ec2Service;
}
// Hand-built test constructions need not supply EC2; a null ec2Service skips subnet resolution.
RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager,
EmulatorConfig config, RegionResolver regionResolver, RedshiftProxyManager proxyManager,
DockerHostResolver dockerHostResolver, RedshiftCredentialBroker credentialBroker,
SecretsManagerService secretsManagerService, ObjectMapper objectMapper,
DynamoDbStreamReader streamReader, RedshiftAuditLogPublisher auditLogPublisher,
RedshiftEventService events, RedshiftIntegrationEventPublisher integrationEvents) {
this(storageFactory, containerManager, config, regionResolver, proxyManager, dockerHostResolver,
credentialBroker, secretsManagerService, objectMapper, streamReader, auditLogPublisher, events,
integrationEvents, null);
}
RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager,
@@ -2261,15 +2278,42 @@ public class RedshiftService implements ManagedSecretRotator {
// ── Cluster Subnet Group Operations ──────────────────────────────────────
public ClusterSubnetGroup createClusterSubnetGroup(String name, String description, String vpcId, List<String> subnetIds) {
return createClusterSubnetGroup(name, description, vpcId, subnetIds, null);
}
public ClusterSubnetGroup createClusterSubnetGroup(String name, String description, String vpcId,
List<String> subnetIds, Map<String, String> tags) {
if (subnetGroups.get(name).isPresent()) {
throw new AwsException("ClusterSubnetGroupAlreadyExists", "Cluster subnet group " + name + " already exists", 400);
}
ClusterSubnetGroup group = new ClusterSubnetGroup(name, description, vpcId, subnetIds);
if (tags != null) {
group.setTags(new LinkedHashMap<>(tags));
}
resolveSubnets(group);
subnetGroups.put(name, group);
subnetGroups.flush();
return group;
}
/**
* Fills the VPC and per-subnet zones from EC2. Subnets EC2 does not know stay unresolved
* rather than failing the call, as this has always accepted arbitrary subnet ids.
*/
private void resolveSubnets(ClusterSubnetGroup group) {
if (ec2Service == null || group.getSubnetIds() == null || group.getSubnetIds().isEmpty()) {
return;
}
Map<String, String> zones = new LinkedHashMap<>();
for (Subnet subnet : ec2Service.describeSubnets(regionResolver.getRegion(), group.getSubnetIds(), Map.of())) {
zones.put(subnet.getSubnetId(), subnet.getAvailabilityZone());
if (group.getVpcId() == null) {
group.setVpcId(subnet.getVpcId());
}
}
group.setSubnetZones(zones);
}
public List<ClusterSubnetGroup> describeClusterSubnetGroups(String name) {
if (name != null && !name.isBlank()) {
// The Terraform AWS provider matches this exact "...Fault" code to detect a missing group.
@@ -2288,6 +2332,8 @@ public class RedshiftService implements ManagedSecretRotator {
}
if (subnetIds != null && !subnetIds.isEmpty()) {
group.setSubnetIds(subnetIds);
group.setVpcId(null);
resolveSubnets(group);
}
subnetGroups.put(name, group);
subnetGroups.flush();
@@ -14,6 +14,8 @@ public class ClusterSubnetGroup {
private String vpcId;
private List<String> subnetIds = new ArrayList<>();
private Map<String, String> tags = new LinkedHashMap<>();
/** Subnet id to availability zone; null on groups persisted before zones were resolved. */
private Map<String, String> subnetZones;
public ClusterSubnetGroup() {}
@@ -34,4 +36,6 @@ public class ClusterSubnetGroup {
public void setSubnetIds(List<String> subnetIds) { this.subnetIds = subnetIds; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
public Map<String, String> getSubnetZones() { return subnetZones; }
public void setSubnetZones(Map<String, String> subnetZones) { this.subnetZones = subnetZones; }
}
@@ -30,6 +30,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static io.github.hectorvent.floci.testing.Ec2Requests.ec2;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
@@ -49,6 +50,9 @@ public class RedshiftOperationsTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260822/us-east-1/redshift/aws4_request";
private static final String EC2_ACCOUNT = "000000000000";
private static final String EC2_REGION = "us-east-1";
private static final String GRANT_NAMES_PATH = "DescribeSnapshotCopyGrantsResponse"
+ ".DescribeSnapshotCopyGrantsResult.SnapshotCopyGrants.SnapshotCopyGrant.SnapshotCopyGrantName";
private static final String MARKER_PATH =
@@ -523,6 +527,57 @@ public class RedshiftOperationsTest {
.body(containsString("<ClusterIdentifier>cluster-restored</ClusterIdentifier>"));
}
private String ec2Id(String path, RequestSpecification req) {
return req.post("/").then().statusCode(200).extract().path(path);
}
private XmlPath describeSubnetGroup(String name) {
return XmlPath.from(redshift("DescribeClusterSubnetGroups", "ClusterSubnetGroupName", name).asString())
.setRootPath("DescribeClusterSubnetGroupsResponse.DescribeClusterSubnetGroupsResult.ClusterSubnetGroups.ClusterSubnetGroup");
}
@Test
@Order(4)
void clusterSubnetGroupKeepsTagsVpcAndSubnetDetail() {
String vpc = ec2Id("CreateVpcResponse.vpc.vpcId", ec2("CreateVpc", EC2_ACCOUNT, EC2_REGION)
.formParam("CidrBlock", "10.77.0.0/16"));
String subnet = ec2Id("CreateSubnetResponse.subnet.subnetId", ec2("CreateSubnet", EC2_ACCOUNT, EC2_REGION)
.formParam("VpcId", vpc).formParam("CidrBlock", "10.77.1.0/24")
.formParam("AvailabilityZone", "us-east-1b"));
assertEquals(200, redshift("CreateClusterSubnetGroup", "ClusterSubnetGroupName", "sng-tagged",
"Description", "d", "SubnetIds.SubnetIdentifier.1", subnet,
"Tags.Tag.1.Key", "env", "Tags.Tag.1.Value", "dev").statusCode());
// Read back through a separate call, not the create response.
XmlPath group = describeSubnetGroup("sng-tagged");
assertEquals(vpc, group.getString("VpcId"));
assertEquals("Complete", group.getString("SubnetGroupStatus"));
assertEquals(subnet, group.getString("Subnets.Subnet.SubnetIdentifier"));
assertEquals("us-east-1b", group.getString("Subnets.Subnet.SubnetAvailabilityZone.Name"));
assertEquals("Active", group.getString("Subnets.Subnet.SubnetStatus"));
assertEquals("env", group.getString("Tags.Tag.Key"));
assertEquals("dev", group.getString("Tags.Tag.Value"));
XmlPath tagged = XmlPath.from(redshift("DescribeTags", "ResourceName",
"arn:aws:redshift:us-east-1:000000000000:subnetgroup:sng-tagged").asString())
.setRootPath("DescribeTagsResponse.DescribeTagsResult.TaggedResources");
assertEquals("dev", tagged.getString("TaggedResource.Tag.Value"));
// Modify keeps tags and recomputes the VPC from the new subnet list.
String vpc2 = ec2Id("CreateVpcResponse.vpc.vpcId", ec2("CreateVpc", EC2_ACCOUNT, EC2_REGION)
.formParam("CidrBlock", "10.78.0.0/16"));
String subnet2 = ec2Id("CreateSubnetResponse.subnet.subnetId", ec2("CreateSubnet", EC2_ACCOUNT, EC2_REGION)
.formParam("VpcId", vpc2).formParam("CidrBlock", "10.78.1.0/24")
.formParam("AvailabilityZone", "us-east-1c"));
assertEquals(200, redshift("ModifyClusterSubnetGroup", "ClusterSubnetGroupName", "sng-tagged",
"SubnetIds.SubnetIdentifier.1", subnet2).statusCode());
group = describeSubnetGroup("sng-tagged");
assertEquals(vpc2, group.getString("VpcId"));
assertEquals("us-east-1c", group.getString("Subnets.Subnet.SubnetAvailabilityZone.Name"));
assertEquals("dev", group.getString("Tags.Tag.Value"));
}
@Test
@Order(4)
void clusterSubnetGroupLifecycle() {
@@ -792,14 +792,14 @@ class RedshiftQueryHandlerTest {
params.putSingle("SubnetIds.SubnetIdentifier.2", "subnet-bbb");
ClusterSubnetGroup group = new ClusterSubnetGroup("test-sng", "desc", null, List.of("subnet-aaa", "subnet-bbb"));
when(service.createClusterSubnetGroup(any(), any(), any(), any())).thenReturn(group);
when(service.createClusterSubnetGroup(any(), any(), any(), any(), any())).thenReturn(group);
Response response = handler.handle("CreateClusterSubnetGroup", params);
assertEquals(200, response.getStatus());
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> captor = ArgumentCaptor.forClass(List.class);
verify(service).createClusterSubnetGroup(eq("test-sng"), eq("desc"), any(), captor.capture());
verify(service).createClusterSubnetGroup(eq("test-sng"), eq("desc"), any(), captor.capture(), any());
assertEquals(List.of("subnet-aaa", "subnet-bbb"), captor.getValue());
}