fix(iam): check Redshift requests on the resources they name (#7287)

Under IAM enforcement, Redshift requests were checked on `*`, so a
grant scoped to a cluster, a snapshot or a database user was refused,
and a deny scoped to one never applied.

The redshift namespace moves from NOT_COVERED to NAMESPACES in the
request resources generator, with corrections where the generated rule
checks the wrong resource. GetClusterCredentials now also gives the
redshift:DbUser condition key, from a new generated table, to its own
check and to the CreateClusterUser check that AutoCreate adds.

Refs #5907

fix(redshift): act only on a snapshot of the cluster the request names

A snapshot request is checked on snapshot:<cluster>/<name> for the
cluster it names, but DeleteClusterSnapshot, RestoreFromClusterSnapshot
and DescribeClusterSnapshots found the snapshot by its name alone. A
caller allowed on one cluster's snapshots could act on a snapshot of
another cluster by naming the allowed one.

A snapshot taken from another cluster than the one the request names,
in SnapshotClusterIdentifier, the cluster of a SnapshotArn, or
DescribeClusterSnapshots' ClusterIdentifier, is now not found.

Refs #5907

chore(iam): generate the Lambda Web and Redshift condition keys into one table

chore(redshift): read a restore's snapshot ARN once
This commit is contained in:
Aymen JAMAAOUI authored and GitHub committed 2026-11-05 11:57:59 -04:00
1 parent ddfc63f6b6
commit 5bcb83b932
22 files changed
+1026 -328

No files matched your search

@@ -17,6 +17,7 @@ import org.junit.jupiter.api.TestFactory;
import java.io.ByteArrayInputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
@@ -280,10 +281,12 @@ class RequestResourceMembersTest {
/**
* Each resource alone, from a request naming it and nothing else, gives exactly its ARN, in the account its
* account member names when it has one, with those sharing its explicit member selector, those the operation
* always names, such as a create's new resource (Cloud Map's {@code CreateService}), and those filled from the ARN
* it is read from (a permission set made in an instance); one named through another resource of its service's
* own, the ARN its service gives for that. A member the table locates in a REST request's path or query is given
* there, and a body or a form giving it another value names nothing.
* always names, such as a create's new resource (Cloud Map's {@code CreateService}), those filled from the ARN
* it is read from (a permission set made in an instance), and those a member it shares fills, their other
* variables open (Redshift's {@code DeleteClusterSnapshot} names {@code cluster:<id>} by the
* {@code SnapshotClusterIdentifier} that also fills {@code snapshot:<id>/<name>}); one named through another
* resource of its service's own, the ARN its service gives for that. A member the table locates in a REST
* request's path or query is given there, and a body or a form giving it another value names nothing.
*/
@TestFactory
Stream<DynamicTest> everyResourceOfTheTableIsReadFromAJsonBodyAndAForm() {
@@ -329,14 +332,15 @@ class RequestResourceMembersTest {
form.append('&').append(parameter(member)).append('=').append(encoded(sent));
});
List<String> named = operation.getValue().stream()
.filter(other -> (other == resource || named(other) || fillsFromTheArn(other, resource)
.filter(other -> (other == resource || named(other) || sharesAMember(other, given)
|| fillsFromTheArn(other, resource)
|| !other.find().isEmpty() && other.find().equals(resource.find())
&& other.when().equals(resource.when()) && other.unless().equals(resource.unless()))
&& (other.endpoint() == null || resource.endpoint() == null
|| other.endpoint().equals(resource.endpoint())))
.map(other -> other == resource ? expected : expected(
table.formats().get(namespace).get(other.types().getFirst()).format(), other,
"000000000000"))
"000000000000", given.keySet()))
.distinct().toList();
StoredResourceArns stored = runningOn(namespace, arn);
assertEquals(named, RequestResources.of(operation.getKey(),
@@ -411,6 +415,25 @@ class RequestResourceMembersTest {
};
}
/**
* Whether a request giving these members names the resource too: it fills a variable from one of them, not from
* the ARN one holds ({@link #fillsFromTheArn} decides those), and no {@code when} or {@code unless} the request's
* values fail leaves it out (each member given is {@code x}, any other absent, which a value list holds as
* {@code ""}).
*/
private static boolean sharesAMember(Resource resource, Map<Member, String> given) {
if (resource.arn() != null || resource.fill().values().stream()
.noneMatch(member -> given.containsKey(member) && !resource.arnOf().containsKey(member.path()))) {
return false;
}
Map<String, String> values = given.entrySet().stream()
.collect(Collectors.toMap(entry -> entry.getKey().name(), Map.Entry::getValue, (a, b) -> a));
return resource.when().entrySet().stream()
.allMatch(when -> when.getValue().contains(values.getOrDefault(when.getKey(), "")))
&& resource.unless().entrySet().stream()
.noneMatch(unless -> unless.getValue().contains(values.getOrDefault(unless.getKey(), "")));
}
/** The value at the member's path in a body: in its list's first element, and in its field's structure. */
private static void put(ObjectNode body, Member member, String value) {
if (member.field() == null) {
@@ -438,10 +461,17 @@ class RequestResourceMembersTest {
/** The format in the account with each variable the resource fills {@code x}, and each other open. */
private static String expected(String format, Resource resource, String account) {
return expected(format, resource, account, resource.fill().values());
}
/** The format in the account with each variable the resource fills from one of {@code given} {@code x}. */
private static String expected(String format, Resource resource, String account, Collection<Member> given) {
String arn = format.replace("${Partition}", "aws").replace("${Region}", "us-east-1")
.replace("${Account}", account);
for (String variable : resource.fill().keySet()) {
arn = arn.replace("${" + variable + "}", "x");
for (Map.Entry<String, Member> variable : resource.fill().entrySet()) {
if (given.contains(variable.getValue())) {
arn = arn.replace("${" + variable.getKey() + "}", "x");
}
}
for (Map.Entry<String, String> variable : resource.fixed().entrySet()) {
arn = arn.replace("${" + variable.getKey() + "}", variable.getValue());
@@ -808,6 +808,26 @@ class RequestResourcesTest {
json("{\"names\":[\"" + project + "a\",\"" + project + "b\"]}")));
}
/**
* A member two resources share names both: Redshift's {@code SnapshotClusterIdentifier} fills the cluster and the
* snapshot's cluster, the snapshot's name open when the request gives none. GetClusterCredentials' database is
* named only when its {@code DbName} is given, though {@code ClusterIdentifier} fills its cluster.
*/
@Test
void aMemberTwoResourcesShareNamesBoth() {
String redshift = "arn:aws:redshift:us-east-1:000000000000:";
assertEquals(List.of(redshift + "cluster:prod", redshift + "snapshot:prod/backup-1"),
of("redshift:DeleteClusterSnapshot",
form("Action=DeleteClusterSnapshot&SnapshotClusterIdentifier=prod&SnapshotIdentifier=backup-1")));
assertEquals(List.of(redshift + "cluster:prod", redshift + "snapshot:prod/*"),
of("redshift:DeleteClusterSnapshot", form("Action=DeleteClusterSnapshot&SnapshotClusterIdentifier=prod")));
assertEquals(List.of(redshift + "dbuser:prod/analyst"), of("redshift:GetClusterCredentials",
form("Action=GetClusterCredentials&ClusterIdentifier=prod&DbUser=analyst")));
assertEquals(List.of(redshift + "dbname:prod/dev", redshift + "dbuser:prod/analyst"),
of("redshift:GetClusterCredentials",
form("Action=GetClusterCredentials&ClusterIdentifier=prod&DbUser=analyst&DbName=dev")));
}
@Test
void aRequestNamingNoResourceOrOfANamespaceTheTableDoesNotReadIsCheckedOnStar() {
assertEquals(List.of(), of("ecr:DescribeRepositories", json("{}")));
@@ -1631,6 +1631,78 @@ class IamRequestResourceEnforcementIntegrationTest {
}
/** A monthly cost budget of the name, with a billing view ARN when one is given. */
/**
* A Redshift parameter group is checked on {@code parametergroup:<name>}, the ARN its handler tags it under, and a
* tag request on the ARN its {@code ResourceName} gives, a member whose name does not end in Arn.
*/
@Test
void aRedshiftParameterGroupIsCheckedOnTheArnItsHandlerMints() {
String name = "res-pg-" + suffix();
admin("redshift").formParam("Action", "CreateClusterParameterGroup").formParam("Version", "2012-12-01")
.formParam("ParameterGroupName", name).formParam("ParameterGroupFamily", "redshift-1.0")
.formParam("Description", "d").post("/").then().statusCode(200);
cleanup.register(() -> admin("redshift").formParam("Action", "DeleteClusterParameterGroup")
.formParam("Version", "2012-12-01").formParam("ParameterGroupName", name).post("/"));
String arn = REDSHIFT + "parametergroup:" + name;
User user = user("res-redshift-pg");
user.policy(allowOn("redshift:CreateTags", arn) + "," + allowOn("redshift:DescribeClusterParameters", arn));
redshiftTag(user, arn).statusCode(200);
refused(redshiftTag(user, arn + "-other"), "redshift:CreateTags");
user.query("redshift", "DescribeClusterParameters").formParam("Version", "2012-12-01")
.formParam("ParameterGroupName", name).post("/").then().statusCode(200);
refused(user.query("redshift", "DescribeClusterParameters").formParam("Version", "2012-12-01")
.formParam("ParameterGroupName", name + "-other").post("/").then(), "redshift:DescribeClusterParameters");
admin("redshift").formParam("Action", "DescribeTags").formParam("Version", "2012-12-01")
.formParam("ResourceName", arn).post("/").then().statusCode(200)
.body("DescribeTagsResponse.DescribeTagsResult.TaggedResources.TaggedResource.ResourceName",
equalTo(arn));
}
/** A Redshift cluster is checked on {@code cluster:<identifier>}, before the cluster is looked up. */
@Test
void aRedshiftClusterIsCheckedOnItsIdentifier() {
String cluster = "res-cluster-" + suffix();
User user = user("res-redshift-cluster");
user.policy(allowOn("redshift:DescribeClusters", REDSHIFT + "cluster:" + cluster));
describeCluster(user, cluster).statusCode(404).body(containsString("ClusterNotFound"));
refused(describeCluster(user, cluster + "-other"), "redshift:DescribeClusters");
}
/**
* A restore is checked on the snapshot of the cluster its {@code SnapshotClusterIdentifier} names, the cluster the
* snapshot was taken from, and on the new cluster its {@code ClusterIdentifier} names.
*/
@Test
void aRedshiftRestoreIsCheckedOnTheSnapshotOfItsSourceCluster() {
String source = "res-source-" + suffix();
String restored = "res-restored-" + suffix();
User user = user("res-redshift-restore");
user.policy(allowOn("redshift:RestoreFromClusterSnapshot", REDSHIFT + "cluster:" + restored) + ","
+ allowOn("redshift:RestoreFromClusterSnapshot", REDSHIFT + "snapshot:" + source + "/snap"));
restore(user, restored, source).statusCode(404).body(containsString("ClusterSnapshotNotFound"));
user.policy(allowOn("redshift:RestoreFromClusterSnapshot", REDSHIFT + "cluster:" + restored) + ","
+ allowOn("redshift:RestoreFromClusterSnapshot", REDSHIFT + "snapshot:" + restored + "/snap"));
refused(restore(user, restored, source), "redshift:RestoreFromClusterSnapshot");
}
private static ValidatableResponse redshiftTag(User user, String arn) {
return user.query("redshift", "CreateTags").formParam("Version", "2012-12-01").formParam("ResourceName", arn)
.formParam("Tags.Tag.1.Key", "team").formParam("Tags.Tag.1.Value", "data").post("/").then();
}
private static ValidatableResponse describeCluster(User user, String cluster) {
return user.query("redshift", "DescribeClusters").formParam("Version", "2012-12-01")
.formParam("ClusterIdentifier", cluster).post("/").then();
}
private static ValidatableResponse restore(User user, String cluster, String snapshotCluster) {
return user.query("redshift", "RestoreFromClusterSnapshot").formParam("Version", "2012-12-01")
.formParam("ClusterIdentifier", cluster).formParam("SnapshotIdentifier", "snap")
.formParam("SnapshotClusterIdentifier", snapshotCluster).post("/").then();
}
private static String budget(String name, String billingViewArn) {
return "{\"BudgetName\":\"" + name + "\",\"BudgetType\":\"COST\",\"TimeUnit\":\"MONTHLY\",\"BudgetLimit\":"
+ "{\"Amount\":\"100\",\"Unit\":\"USD\"}" + (billingViewArn == null ? ""
@@ -117,14 +117,74 @@ class RedshiftGetClusterCredentialsIamEnforcementIntegrationTest {
assertClusterNotFound(credentials(accessKeyId, cluster).formParam("AutoCreate", "false"));
}
/** The Management Guide's policy grants GetClusterCredentials on one {@code dbuser} alone. */
@Test
void getClusterCredentials_grantOnTheDbUser_passesTheIamCheckForThatUserOnly() {
String cluster = uniqueName("gcc-dbuser");
String user = uniqueName("gcc-dbuser");
String accessKeyId = createUser(user);
userPolicy(user, allow("redshift:GetClusterCredentials", ARN_PREFIX + "dbuser:" + cluster + "/analyst"));
assertClusterNotFound(credentials(accessKeyId, cluster));
assertDenied(credentials(accessKeyId, cluster, "intruder"));
}
/** "If the DbName parameter is specified, the IAM policy must allow access to the resource dbname". */
@Test
void getClusterCredentials_dbName_needsAGrantOnTheDatabase() {
String cluster = uniqueName("gcc-dbname");
String user = uniqueName("gcc-dbname");
String accessKeyId = createUser(user);
userPolicy(user, allow("redshift:GetClusterCredentials", ARN_PREFIX + "dbuser:" + cluster + "/analyst"));
assertDenied(credentials(accessKeyId, cluster).formParam("DbName", "testdb"));
userPolicy(user, allow("redshift:GetClusterCredentials", ARN_PREFIX + "dbuser:" + cluster + "/analyst") + ","
+ allow("redshift:GetClusterCredentials", ARN_PREFIX + "dbname:" + cluster + "/testdb"));
assertClusterNotFound(credentials(accessKeyId, cluster).formParam("DbName", "testdb"));
}
/**
* The Management Guide's example 8 scopes GetClusterCredentials and CreateClusterUser to
* {@code dbuser:<cluster>/${redshift:DbUser}}, the user the request names.
*/
@Test
void getClusterCredentials_dbUserPolicyVariable_coversBothActions() {
String cluster = uniqueName("gcc-variable");
String user = uniqueName("gcc-variable");
String accessKeyId = createUser(user);
String ownUser = ARN_PREFIX + "dbuser:" + cluster + "/${redshift:DbUser}";
userPolicy(user, allow("redshift:GetClusterCredentials", ownUser) + ","
+ allow("redshift:CreateClusterUser", ownUser));
assertClusterNotFound(credentials(accessKeyId, cluster).formParam("AutoCreate", "true"));
}
/** A condition on {@code redshift:DbUser} applies to both actions, CreateClusterUser's included. */
@Test
void getClusterCredentials_dbUserCondition_appliesToCreateClusterUser() {
String cluster = uniqueName("gcc-condition");
String user = uniqueName("gcc-condition");
String accessKeyId = createUser(user);
userPolicy(user, allow("redshift:GetClusterCredentials", "*") + ","
+ "{\"Effect\":\"Allow\",\"Action\":\"redshift:CreateClusterUser\",\"Resource\":\"*\","
+ "\"Condition\":{\"StringEquals\":{\"redshift:DbUser\":\"analyst\"}}}");
assertClusterNotFound(credentials(accessKeyId, cluster).formParam("AutoCreate", "true"));
assertDenied(credentials(accessKeyId, cluster, "intruder").formParam("AutoCreate", "true"));
}
private static RequestSpecification credentials(String accessKeyId, String cluster) {
return credentials(accessKeyId, cluster, "analyst");
}
private static RequestSpecification credentials(String accessKeyId, String cluster, String dbUser) {
return given()
.header("Authorization", auth(accessKeyId, "redshift"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetClusterCredentials")
.formParam("Version", "2012-12-01")
.formParam("ClusterIdentifier", cluster)
.formParam("DbUser", "analyst");
.formParam("DbUser", dbUser);
}
private static void assertDenied(RequestSpecification request) {
@@ -597,7 +597,7 @@ class RedshiftQueryHandlerTest {
params.putSingle("SnapshotIdentifier", "test-snapshot");
Snapshot snapshot = new Snapshot("test-snapshot", "test-cluster", "deleted", 5439, "admin");
when(service.deleteSnapshot("test-snapshot")).thenReturn(snapshot);
when(service.deleteSnapshot("test-snapshot", null)).thenReturn(snapshot);
Response response = handler.handle("DeleteClusterSnapshot", params);
assertEquals(200, response.getStatus());
@@ -619,7 +619,7 @@ class RedshiftQueryHandlerTest {
cluster.setMasterUsername("admin");
cluster.setClusterStatus("available");
cluster.setEndpoint(new Endpoint("localhost", 5439));
when(service.restoreFromClusterSnapshot("restored-cluster", "test-snapshot", "dc2.large")).thenReturn(cluster);
when(service.restoreFromClusterSnapshot("restored-cluster", "test-snapshot", null, "dc2.large")).thenReturn(cluster);
Response response = handler.handle("RestoreFromClusterSnapshot", params);
assertEquals(200, response.getStatus());
@@ -636,11 +636,11 @@ class RedshiftQueryHandlerTest {
params.putSingle("ClusterIdentifier", "restored-cluster");
params.putSingle("SnapshotArn", "arn:aws:redshift:us-east-1:acc:snapshot:src/my-snap");
Cluster cluster = availableCluster("restored-cluster");
when(service.restoreFromClusterSnapshot("restored-cluster", "my-snap", null)).thenReturn(cluster);
when(service.restoreFromClusterSnapshot("restored-cluster", "my-snap", "src", null)).thenReturn(cluster);
Response response = handler.handle("RestoreFromClusterSnapshot", params, "auth");
assertEquals(200, response.getStatus());
verify(service).restoreFromClusterSnapshot("restored-cluster", "my-snap", null);
verify(service).restoreFromClusterSnapshot("restored-cluster", "my-snap", "src", null);
}
@Test
@@ -674,7 +674,7 @@ class RedshiftQueryHandlerTest {
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("RestoreFromClusterSnapshot", params, "auth"));
assertEquals("ClusterSnapshotNotFound", ex.getErrorCode());
verify(service, never()).restoreFromClusterSnapshot(any(), any(), any());
verify(service, never()).restoreFromClusterSnapshot(any(), any(), any(), any());
}
@Test
@@ -688,7 +688,59 @@ class RedshiftQueryHandlerTest {
() -> handler.handle("RestoreFromClusterSnapshot", params, "auth"));
assertEquals("InvalidParameterCombination", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
verify(service, never()).restoreFromClusterSnapshot(any(), any(), any());
verify(service, never()).restoreFromClusterSnapshot(any(), any(), any(), any());
}
/** The cluster a request is authorized on, snapshot:<cluster>/<name>, is the one its snapshot must be of. */
@Test
void deleteClusterSnapshotPassesTheClusterItNamesTheSnapshotBy() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("SnapshotIdentifier", "test-snapshot");
params.putSingle("SnapshotClusterIdentifier", "prod");
Snapshot snapshot = new Snapshot("test-snapshot", "prod", "deleted", 5439, "admin");
when(service.deleteSnapshot("test-snapshot", "prod")).thenReturn(snapshot);
assertEquals(200, handler.handle("DeleteClusterSnapshot", params).getStatus());
verify(service).deleteSnapshot("test-snapshot", "prod");
}
@Test
void restoreFromClusterSnapshotPassesTheClusterItNamesTheSnapshotBy() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "restored-cluster");
params.putSingle("SnapshotIdentifier", "test-snapshot");
params.putSingle("SnapshotClusterIdentifier", "prod");
when(service.restoreFromClusterSnapshot("restored-cluster", "test-snapshot", "prod", null))
.thenReturn(availableCluster("restored-cluster"));
assertEquals(200, handler.handle("RestoreFromClusterSnapshot", params, "auth").getStatus());
verify(service).restoreFromClusterSnapshot("restored-cluster", "test-snapshot", "prod", null);
}
@Test
void restoreFromClusterSnapshotNamingTwoClustersIsNotFound() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "restored-cluster");
params.putSingle("SnapshotArn", "arn:aws:redshift:us-east-1:acc:snapshot:src/my-snap");
params.putSingle("SnapshotClusterIdentifier", "other");
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("RestoreFromClusterSnapshot", params, "auth"));
assertEquals("ClusterSnapshotNotFound", ex.getErrorCode());
assertEquals(404, ex.getHttpStatus());
verify(service, never()).restoreFromClusterSnapshot(any(), any(), any(), any());
}
@Test
void restoreFromClusterSnapshotArnWithoutAClusterIsNotFound() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "restored-cluster");
params.putSingle("SnapshotArn", "arn:aws:redshift:us-east-1:acc:snapshot:/my-snap");
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("RestoreFromClusterSnapshot", params, "auth"));
assertEquals("ClusterSnapshotNotFound", ex.getErrorCode());
verify(service, never()).restoreFromClusterSnapshot(any(), any(), any(), any());
}
@Test
@@ -1749,6 +1749,52 @@ class RedshiftServiceTest {
verify(clusterBackend, atLeastOnce()).flush();
}
/**
* A request is authorized on snapshot:<cluster>/<name> for the cluster it names, so a snapshot of the same name
* taken from another cluster is not found, and nothing is restored, deleted or described.
*/
@Test
void restoreFromClusterSnapshotOfAnotherClusterIsNotFound() {
when(snapshotBackend.get("snap-1")).thenReturn(Optional.of(snapshotOf("snap-1", "protected")));
when(clusterBackend.get("c1")).thenReturn(Optional.empty());
AwsException ex = assertThrows(AwsException.class,
() -> service.restoreFromClusterSnapshot("c1", "snap-1", "allowed", null));
assertEquals("ClusterSnapshotNotFound", ex.getErrorCode());
assertEquals(404, ex.getHttpStatus());
verify(clusterBackend, never()).put(eq("c1"), any());
verifyNoInteractions(cm);
}
@Test
void deleteSnapshotOfAnotherClusterIsNotFoundAndKept() {
when(snapshotBackend.get("snap-1")).thenReturn(Optional.of(snapshotOf("snap-1", "protected")));
AwsException ex = assertThrows(AwsException.class, () -> service.deleteSnapshot("snap-1", "allowed"));
assertEquals("ClusterSnapshotNotFound", ex.getErrorCode());
verify(snapshotBackend, never()).delete("snap-1");
service.deleteSnapshot("snap-1", "protected");
verify(snapshotBackend).delete("snap-1");
}
@Test
void describeSnapshotsByIdentifierOfAnotherClusterIsNotFound() {
when(snapshotBackend.get("snap-1")).thenReturn(Optional.of(snapshotOf("snap-1", "protected")));
AwsException ex = assertThrows(AwsException.class, () -> service.describeSnapshots("snap-1", "allowed"));
assertEquals("ClusterSnapshotNotFound", ex.getErrorCode());
assertEquals(1, service.describeSnapshots("snap-1", "protected").size());
}
private static Snapshot snapshotOf(String snapshotIdentifier, String clusterIdentifier) {
Snapshot snapshot = new Snapshot();
snapshot.setSnapshotIdentifier(snapshotIdentifier);
snapshot.setClusterIdentifier(clusterIdentifier);
snapshot.setSnapshotType("manual");
return snapshot;
}
@Test
void restoreFromClusterSnapshotKeepsMetadataWhenProxyStopFails() {
when(clusterBackend.accountId()).thenReturn("111111111111");