fix(redshift): scope clusters to the Region they were created in (#8421)

A Redshift cluster is Regional, but Floci found clusters by identifier
alone, so DescribeClusters in one Region listed a cluster created in
another, and that Region could modify, pause, reboot, snapshot or delete
it. Every call naming a cluster now finds it only in the Region it was
created in, through regionalCluster, and answers ClusterNotFound
elsewhere; DescribeClusters and DescribeTags list only the request
Region's clusters. A managed password rotation refuses changes only in
its cluster's Region, so it is not seen from another.

Work done outside a request, such as snapshot copies, zero-ETL, Firehose
delivery and metrics, still finds a cluster in any Region, and a cluster
identifier stays unique across the account, as the CreateCluster
reference documents.

Part of #8218
This commit is contained in:
mrfelek authored and GitHub committed 2026-11-15 00:32:09 -04:00
1 parent 0baf1a1b79
commit 35a9ca0f4b
3 files changed
+159 -65

No files matched your search

@@ -167,9 +167,14 @@ public class RedshiftService implements ManagedSecretRotator {
});
}
/**
* Refuses a change to the request Region's cluster {@code identifier} while its managed master password is being
* rotated. A cluster of another Region is left to the change's own lookup, which answers ClusterNotFound there, so
* its rotation is not seen from other Regions.
*/
private void ensureNoManagedRotation(String accountId, String identifier) {
ResourceKey key = new ResourceKey(accountId, "cluster", identifier);
if (managedRotationReservations.containsValue(key)) {
if (managedRotationReservations.containsValue(key) && regionalCluster(identifier).isPresent()) {
throw new AwsException("InvalidRequestException",
"The cluster's managed master password is being rotated. Try again after rotation completes.", 400);
}
@@ -1163,13 +1168,9 @@ public class RedshiftService implements ManagedSecretRotator {
public List<Cluster> describeClusters(String identifier) {
if (identifier != null) {
Optional<Cluster> cluster = clusters.get(identifier);
if (cluster.isEmpty()) {
throw new AwsException("ClusterNotFound", "Cluster " + identifier + " not found", 404);
}
return List.of(cluster.get());
return List.of(requireCluster(identifier));
}
return clusters.scan(k -> true);
return regionalClusters();
}
/** The caller's cluster an ARN names, when the ARN is exactly that cluster's in this Region. */
@@ -1182,7 +1183,7 @@ public class RedshiftService implements ManagedSecretRotator {
return Optional.empty();
}
String identifier = arn.resource().substring("cluster:".length());
return clusters.get(identifier).filter(cluster -> clusterArn.equals(clusterArn(identifier)));
return regionalCluster(identifier).filter(cluster -> clusterArn.equals(clusterArn(identifier)));
}
/** Sets, or with {@code null} removes, the resource policy of the caller's cluster an ARN names. */
@@ -1247,11 +1248,7 @@ public class RedshiftService implements ManagedSecretRotator {
throw new AwsException("InvalidRetentionPeriodFault",
"FinalClusterSnapshotRetentionPeriod must be -1 or between 1 and 3653", 400);
}
Optional<Cluster> clusterOpt = clusters.get(identifier);
if (clusterOpt.isEmpty()) {
throw new AwsException("ClusterNotFound", "Cluster " + identifier + " not found", 404);
}
Cluster cluster = clusterOpt.get();
Cluster cluster = requireCluster(identifier);
if (!skipSnapshot) {
if (!"available".equals(cluster.getClusterStatus())) {
@@ -1355,8 +1352,7 @@ public class RedshiftService implements ManagedSecretRotator {
String masterUserPassword, String clusterParameterGroupName,
List<String> vpcSecurityGroupIds, Boolean multiAZ,
Integer automatedRetention) {
Cluster cluster = clusters.get(clusterIdentifier)
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
Cluster cluster = requireCluster(clusterIdentifier);
rejectPausedCluster(cluster);
validateAutomatedRetention(nodeType == null ? cluster.getNodeType() : nodeType,
automatedRetention == null ? cluster.getAutomatedSnapshotRetentionPeriod() : automatedRetention);
@@ -1432,8 +1428,7 @@ public class RedshiftService implements ManagedSecretRotator {
private Cluster modifyClusterIamRolesLocked(String clusterIdentifier, List<String> addIamRoles,
List<String> removeIamRoles, String defaultIamRoleArn) {
Cluster cluster = clusters.get(clusterIdentifier)
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
Cluster cluster = requireCluster(clusterIdentifier);
// Validate every ARN before mutating: the cluster object is a live reference from HybridStorage.
addIamRoles.forEach(RedshiftService::requireIamRoleArn);
@@ -1598,8 +1593,7 @@ public class RedshiftService implements ManagedSecretRotator {
}
public Cluster describeLoggingStatus(String clusterIdentifier) {
return clusters.get(clusterIdentifier)
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
return requireCluster(clusterIdentifier);
}
public Cluster enableLogging(String clusterIdentifier, String bucketName, String s3KeyPrefix,
@@ -1617,8 +1611,7 @@ public class RedshiftService implements ManagedSecretRotator {
private Cluster enableLoggingLocked(String clusterIdentifier, String bucketName, String s3KeyPrefix,
String logDestinationType, List<String> logExports,
String s3TableKmsKeyId, String s3TableGranularity) {
Cluster cluster = clusters.get(clusterIdentifier)
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
Cluster cluster = requireCluster(clusterIdentifier);
String destination = "s3";
if (logDestinationType != null && !logDestinationType.isBlank()) {
@@ -1725,8 +1718,7 @@ public class RedshiftService implements ManagedSecretRotator {
}
private Cluster disableLoggingLocked(String clusterIdentifier) {
Cluster cluster = clusters.get(clusterIdentifier)
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
Cluster cluster = requireCluster(clusterIdentifier);
cluster.setLoggingEnabled(false);
cluster.setLoggingGeneration(cluster.getLoggingGeneration() + 1);
cluster.setLoggingBucketName(null);
@@ -1837,8 +1829,7 @@ public class RedshiftService implements ManagedSecretRotator {
}
private Cluster clusterInState(String identifier, String requiredState) {
Cluster cluster = clusters.get(identifier).orElseThrow(() ->
new AwsException("ClusterNotFound", "Cluster " + identifier + " not found", 404));
Cluster cluster = requireCluster(identifier);
if (!requiredState.equals(cluster.getClusterStatus())) {
throw new AwsException("InvalidClusterState", "Cluster " + identifier
+ " must be " + requiredState + " for this operation", 400);
@@ -1873,8 +1864,7 @@ public class RedshiftService implements ManagedSecretRotator {
}
private Cluster rebootClusterLocked(String clusterIdentifier) {
Cluster cluster = clusters.get(clusterIdentifier)
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
Cluster cluster = requireCluster(clusterIdentifier);
rejectPausedCluster(cluster);
// Replacement containers do not reattach the old anonymous volume, so a plain stop+recreate
@@ -2027,12 +2017,8 @@ public class RedshiftService implements ManagedSecretRotator {
private Snapshot createSnapshot(String snapshotIdentifier, String clusterIdentifier, Integer retentionPeriod,
Map<String, String> tags) {
validateSnapshotIdentifier(snapshotIdentifier);
Optional<Cluster> clusterOpt = clusters.get(clusterIdentifier);
if (clusterOpt.isEmpty()) {
throw new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404);
}
return createSnapshot(clusters.accountId(), snapshotIdentifier, clusterOpt.get(), retentionPeriod,
Instant.now(), null, tags);
return createSnapshot(clusters.accountId(), snapshotIdentifier, requireCluster(clusterIdentifier),
retentionPeriod, Instant.now(), null, tags);
}
private Snapshot createSnapshot(String accountId, String snapshotIdentifier, Cluster cluster,
@@ -2197,6 +2183,30 @@ public class RedshiftService implements ManagedSecretRotator {
return named;
}
/**
* The calling account's cluster {@code identifier}, when it is in the request's Region. Clusters are
* Regional, each in the Region it was created in ({@link #clusterRegion(Cluster)}); identifiers stay unique
* across an account's Regions, so the checks that a new one is free still look in every Region.
*/
private Optional<Cluster> regionalCluster(String identifier) {
return clusters.get(identifier).filter(this::isInRequestRegion);
}
/** {@link #regionalCluster}, answering ClusterNotFound when the request's Region has no such cluster. */
private Cluster requireCluster(String clusterIdentifier) {
return regionalCluster(clusterIdentifier)
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
}
/** The calling account's clusters in the request's Region. */
private List<Cluster> regionalClusters() {
return clusters.scan(k -> true).stream().filter(this::isInRequestRegion).toList();
}
private boolean isInRequestRegion(Cluster cluster) {
return clusterRegion(cluster).equals(regionResolver.getRegion());
}
/**
* The snapshot an ARN names in its account, as a restore finds it, a cluster the ARN leaves open ({@code *})
* matching any: in the caller's account the copy kept in the ARN's Region before the snapshot itself, and in
@@ -2955,7 +2965,7 @@ public class RedshiftService implements ManagedSecretRotator {
/** Whether the named source exists; Floci does not model cluster security groups or scheduled actions. */
private boolean eventSourceExists(String sourceType, String sourceIdentifier) {
return switch (sourceType) {
case RedshiftEventCatalog.CLUSTER -> clusters.get(sourceIdentifier).isPresent();
case RedshiftEventCatalog.CLUSTER -> regionalCluster(sourceIdentifier).isPresent();
case RedshiftEventCatalog.PARAMETER_GROUP -> DEFAULT_PARAMETER_GROUP_NAME.equals(sourceIdentifier)
|| parameterGroups.get(sourceIdentifier).isPresent();
case RedshiftEventCatalog.SNAPSHOT -> findSnapshot(sourceIdentifier).isPresent();
@@ -3187,11 +3197,6 @@ public class RedshiftService implements ManagedSecretRotator {
// AWS reports -1 ("retain indefinitely") when ManualSnapshotRetentionPeriod is not given.
private static final int RETAIN_MANUAL_SNAPSHOTS_INDEFINITELY = -1;
private Cluster requireCluster(String clusterIdentifier) {
return clusters.get(clusterIdentifier)
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
}
// Automated snapshots: 1 to 35 days.
private static void validateAutomatedRetention(int days) {
if (days < 1 || days > 35) {
@@ -3793,7 +3798,7 @@ public class RedshiftService implements ManagedSecretRotator {
Integer maxRecords, String marker) {
String clusterSchedule = null;
if (clusterIdentifier != null && !clusterIdentifier.isBlank()) {
clusterSchedule = clusters.get(clusterIdentifier).map(Cluster::getSnapshotScheduleIdentifier).orElse(null);
clusterSchedule = regionalCluster(clusterIdentifier).map(Cluster::getSnapshotScheduleIdentifier).orElse(null);
if (clusterSchedule == null) {
return new PaginatedResult<>(List.of(), null);
}
@@ -3911,7 +3916,7 @@ public class RedshiftService implements ManagedSecretRotator {
return result;
}
if (resourceType == null || "cluster".equalsIgnoreCase(resourceType)) {
for (Cluster c : clusters.scan(k -> true)) {
for (Cluster c : regionalClusters()) {
addTaggedResources(result, clusterArn(c.getClusterIdentifier()), "cluster", c.getTags(), tagKeysFilter);
}
}
@@ -4068,8 +4073,7 @@ public class RedshiftService implements ManagedSecretRotator {
yield new TagHandle(subscription.getTags(), updated -> eventService().replaceSubscriptionTags(id, updated));
}
case "cluster" -> {
Cluster cluster = clusters.get(id)
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + id + " not found", 404));
Cluster cluster = requireCluster(id);
yield new TagHandle(cluster.getTags(), updated -> {
cluster.setTags(updated);
clusters.put(id, cluster);
@@ -42,6 +42,7 @@ import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
@@ -384,6 +385,107 @@ class RedshiftServiceTest {
return cluster;
}
/**
* A cluster is Regional: it is listed and found only in the Region it was created in, and every call
* naming it from another Region of the account answers ClusterNotFound.
*/
@Test
void aClusterIsListedAndFoundOnlyInTheRegionItWasCreatedIn() {
Cluster cluster = storedCluster("analytics", "us-east-1");
cluster.setTags(Map.of("team", "data"));
when(clusterBackend.scan(any())).thenReturn(List.of(cluster));
RedshiftService west = serviceIn("eu-west-1");
assertEquals(List.of(cluster), service.describeClusters(null));
assertEquals(List.of(cluster), service.describeClusters("analytics"));
assertEquals(List.of(new RedshiftService.TaggedResource(
"arn:aws:redshift:us-east-1:111111111111:cluster:analytics", "cluster", "team", "data")),
service.describeTags(null, "cluster", null));
assertEquals(List.of(), west.describeClusters(null));
assertEquals(List.of(), west.describeTags(null, "cluster", null));
assertEquals(Optional.empty(), west.findClusterByArn("arn:aws:redshift:eu-west-1:111111111111:cluster:analytics"));
for (Executable call : List.<Executable>of(
() -> west.describeClusters("analytics"),
() -> west.modifyCluster("analytics", null, null, null, null, List.of()),
() -> west.modifyClusterIamRoles("analytics", List.of(), List.of()),
() -> west.describeLoggingStatus("analytics"),
() -> west.enableLogging("analytics", null, null, "cloudwatch", List.of("connectionlog")),
() -> west.disableLogging("analytics"),
() -> west.pauseCluster("analytics"),
() -> west.resumeCluster("analytics"),
() -> west.rebootCluster("analytics"),
() -> west.createSnapshot("nightly", "analytics"),
() -> west.enableSnapshotCopy("analytics", "us-west-2", null, null, null),
() -> west.modifyClusterSnapshotSchedule("analytics", null, true),
() -> west.createTags("arn:aws:redshift:eu-west-1:111111111111:cluster:analytics", Map.of("k", "v")),
() -> west.deleteCluster("analytics"))) {
assertEquals("ClusterNotFound", assertThrows(AwsException.class, call).getErrorCode());
}
verify(clusterBackend, never()).put(any(), any());
verify(clusterBackend, never()).delete(any());
}
/**
* Work done outside a request on a cluster's behalf learns its Region: the one it was created in, and the
* default Region for a cluster stored before clusters kept one.
*/
@Test
void aClustersRegionIsTheOneItWasCreatedIn() {
storedCluster("analytics", "eu-west-1");
storedCluster("legacy", null);
RedshiftService west = serviceIn("eu-west-1");
assertEquals(Optional.of("eu-west-1"), service.clusterRegion("111111111111", "analytics"));
assertEquals(Optional.of("us-east-1"), west.clusterRegion("111111111111", "legacy"));
assertEquals(Optional.empty(), service.clusterRegion("111111111111", "missing"));
}
/**
* A managed master password rotation refuses changes to its cluster in the cluster's Region only: from another
* Region the cluster is not found, as for any change there, so its rotation is not seen.
*/
@Test
void aRotatingClusterIsNotFoundFromAnotherRegion() {
Cluster cluster = storedCluster("managed-cluster", "us-east-1");
cluster.setMasterPasswordSecretArn("arn:aws:secretsmanager:us-east-1:111111111111:secret:redshift-managed");
when(clusterBackend.scanAllAccountEntries(any())).thenReturn(List.of(
new AccountAwareStorageBackend.AccountEntry<>("111111111111", "managed-cluster", cluster)));
RedshiftService west = serviceIn("eu-west-1");
for (RedshiftService rotating : List.of(service, west)) {
rotating.reserve(cluster.getMasterPasswordSecretArn(), "us-east-1");
String expected = rotating == service ? "InvalidRequestException" : "ClusterNotFound";
try {
assertEquals(expected, assertThrows(AwsException.class,
() -> rotating.deleteCluster("managed-cluster")).getErrorCode());
assertEquals(expected, assertThrows(AwsException.class,
() -> rotating.rebootCluster("managed-cluster")).getErrorCode());
} finally {
rotating.release(cluster.getMasterPasswordSecretArn(), "us-east-1");
}
}
verify(cm, never()).stop("111111111111", "managed-cluster");
}
/** An available cluster stored in account 111111111111, created in {@code region}; null for none recorded. */
private Cluster storedCluster(String identifier, String region) {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier(identifier);
cluster.setClusterStatus("available");
cluster.setSnapshotRegion(region);
when(clusterBackend.get(identifier)).thenReturn(Optional.of(cluster));
when(clusterBackend.getForAccount("111111111111", identifier)).thenReturn(Optional.of(cluster));
return cluster;
}
/** A service whose calls run in {@code region}, the default Region staying us-east-1. */
private RedshiftService serviceIn(String region) {
RegionResolver resolver = spy(new RegionResolver("us-east-1", "111111111111"));
doReturn(region).when(resolver).getRegion();
return new RedshiftService(sf, cm, config, resolver, proxyManager, dockerHostResolver,
credentialBroker, secretsManagerService, new ObjectMapper(), null, null);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void loggingDestinationRegionSurvivesStorageAndRestart(boolean refresh) throws Exception {
@@ -980,25 +1082,6 @@ class RedshiftServiceTest {
autoCopyConsumer);
}
/**
* Work done outside a request on a cluster's behalf, Redshift Spectrum over JDBC, learns the cluster's Region: the
* one it was created in, and the default Region for a cluster stored before clusters kept one.
*/
@Test
void aClustersRegionIsTheOneItWasCreatedIn() {
Cluster analytics = new Cluster();
analytics.setClusterIdentifier("analytics");
analytics.setSnapshotRegion("eu-west-1");
Cluster legacy = new Cluster();
legacy.setClusterIdentifier("legacy");
when(clusterBackend.getForAccount("111111111111", "analytics")).thenReturn(Optional.of(analytics));
when(clusterBackend.getForAccount("111111111111", "legacy")).thenReturn(Optional.of(legacy));
assertEquals(Optional.of("eu-west-1"), service.clusterRegion("111111111111", "analytics"));
assertEquals(Optional.of("us-east-1"), service.clusterRegion("111111111111", "legacy"));
assertEquals(Optional.empty(), service.clusterRegion("111111111111", "missing"));
}
private static final String ORDERS_TABLE_ARN = "arn:aws:dynamodb:us-east-1:111111111111:table/orders";
private static final String NAMESPACE_ARN = "arn:aws:redshift-serverless:us-east-1:111111111111:namespace/"
+ "8f3e0b52-6c1a-4f0e-9d7b-2a4c5e6f7a8b";
@@ -211,9 +211,10 @@ class RedshiftSnapshotCopyServiceTest {
fixture.service(SOURCE).createSnapshot("nightly", "warehouse");
fixture.service(SOURCE).runSnapshotCopies(Instant.now());
fixture.service(SOURCE).deleteSnapshot("nightly");
seedCluster(fixture, "replica", DESTINATION, null, null);
AwsException refused = assertThrows(AwsException.class,
() -> fixture.service(DESTINATION).createSnapshot("nightly", "warehouse"));
() -> fixture.service(DESTINATION).createSnapshot("nightly", "replica"));
assertEquals("ClusterSnapshotAlreadyExists", refused.getErrorCode());
}
@@ -347,14 +348,20 @@ class RedshiftSnapshotCopyServiceTest {
}
private static Cluster seedCluster(Fixture fixture, String id, Instant copyEnabledAt) {
return seedCluster(fixture, id, SOURCE, DESTINATION, copyEnabledAt);
}
/** An available cluster of {@code region}, copying its snapshots to {@code copyDestination} when not null. */
private static Cluster seedCluster(Fixture fixture, String id, String region, String copyDestination,
Instant copyEnabledAt) {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier(id);
cluster.setNodeType("dc2.large");
cluster.setMasterUsername("admin");
cluster.setMasterPassword("Secret123!");
cluster.setClusterStatus("available");
cluster.setSnapshotRegion(SOURCE);
cluster.setSnapshotCopyDestinationRegion(DESTINATION);
cluster.setSnapshotRegion(region);
cluster.setSnapshotCopyDestinationRegion(copyDestination);
cluster.setSnapshotCopyRetentionPeriod(7);
cluster.setSnapshotCopyManualRetentionPeriod(-1);
cluster.setSnapshotCopyEnabledAt(copyEnabledAt);