fix(dynamodb): enforce the default Select for IAM (#6702)

* fix(dynamodb): enforce effective read selection in IAM policies

Preserve generated action and request-member coverage, effective read projections, PartiQL attributes and independent BatchGetItem contexts. Rebase on current main and scope condition data verification to its vendored file, generator, tests and imported modules, retaining all existing IAM data gates.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(dynamodb): derive transaction read conditions from modeled members

Use the generated transaction Get member paths before GetItem IAM extraction, so ignored legacy projection members cannot authorize whole-item reads.

Signed-off-by: Andre Kurait <akurait@amazon.com>

---------

Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-10-27 10:05:55 -04:00
1 parent 58ce60b06e
commit 52c9c51a7b
22 files changed
+2395 -46

No files matched your search

@@ -419,7 +419,7 @@ class IamConditionContextResolverTest {
assertEquals(List.of("USER_alice"), conditions.get("dynamodb:LeadingKeys"));
assertEquals(List.of("PK"), conditions.get("dynamodb:Attributes"));
assertFalse(conditions.containsKey("dynamodb:Select"));
assertEquals(List.of("ALL_ATTRIBUTES"), conditions.get("dynamodb:Select"));
}
@Test
@@ -455,6 +455,26 @@ class IamConditionContextResolverTest {
assertEquals(List.of("COUNT"), conditions.get("dynamodb:Select"));
}
@Test
void transactionGetContextUsesOnlySupportedMembersWithoutChangingTheRequest() {
when(dynamoDbService.findTable("FgacTable", "us-east-1")).thenReturn(Optional.of(fgacTable()));
for (String extra : List.of("\"AttributesToGet\":[\"ignored\"]", "\"Select\":\"SPECIFIC_ATTRIBUTES\"",
"\"IndexName\":\"ignored\"")) {
ContainerRequestContext request = mock(ContainerRequestContext.class);
JsonNode body = json("{\"TransactItems\":[{\"Get\":{\"TableName\":\"FgacTable\","
+ "\"Key\":{\"PK\":{\"S\":\"USER_alice\"}}," + extra + "}}]}");
JsonNode original = body.deepCopy();
when(request.getProperty("floci.bufferedJsonBody")).thenReturn(body);
Map<String, List<String>> context = resolver.dynamoDbTransactionItems("dynamodb:TransactGetItems",
request, "us-east-1", "000000000000").getFirst().context();
assertEquals(List.of("ALL_ATTRIBUTES"), context.get("dynamodb:Select"));
assertEquals(List.of("PK"), context.get("dynamodb:Attributes"));
assertEquals(List.of("USER_alice"), context.get("dynamodb:LeadingKeys"));
assertEquals(List.of("TransactGetItems"), context.get("dynamodb:EnclosingOperation"));
assertEquals(original, body);
}
}
@Test
void singleItemWritesUseTheirReturnValuesAndExecutionDefault() {
for (String action : List.of("PutItem", "UpdateItem", "DeleteItem")) {
@@ -536,7 +556,7 @@ class IamConditionContextResolverTest {
when(request.getHeaderString("X-Amz-Target")).thenReturn("DynamoDB_20120810.Query");
Map<String, List<String>> modern = resolver.resolve("dynamodb", "dynamodb:Query", request);
assertEquals(List.of("USER_alice"), modern.get("dynamodb:LeadingKeys"));
assertFalse(modern.containsKey("dynamodb:Select"));
assertEquals(List.of("SPECIFIC_ATTRIBUTES"), modern.get("dynamodb:Select"));
}
@Test
@@ -578,6 +598,26 @@ class IamConditionContextResolverTest {
assertEquals(List.of("USER_alice", "USER_bob"), conditions.get("dynamodb:LeadingKeys"));
}
@Test
void batchAliasesRetainIndependentSelections() {
ContainerRequestContext request = mock(ContainerRequestContext.class);
String arn = "arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable";
when(request.getProperty("floci.bufferedJsonBody")).thenReturn(json("""
{"RequestItems":{
"FgacTable":{"Keys":[{"PK":{"S":"USER_alice"}}],"ProjectionExpression":"PK"},
"%s":{"Keys":[{"PK":{"S":"USER_bob"}}]}}}
""".formatted(arn)));
when(dynamoDbService.findTable("FgacTable", "us-east-1")).thenReturn(Optional.of(fgacTable()));
when(dynamoDbService.findTable(arn, "us-east-1")).thenReturn(Optional.of(fgacTable()));
List<Map<String, List<String>>> contexts = resolver.dynamoDbBatchConditionContexts(
"dynamodb:BatchGetItem", request, arn);
assertEquals(2, contexts.size());
assertEquals(List.of("SPECIFIC_ATTRIBUTES"), contexts.get(0).get("dynamodb:Select"));
assertEquals(List.of("ALL_ATTRIBUTES"), contexts.get(1).get("dynamodb:Select"));
assertEquals(List.of("USER_alice"), contexts.get(0).get("dynamodb:LeadingKeys"));
assertEquals(List.of("USER_bob"), contexts.get(1).get("dynamodb:LeadingKeys"));
}
@Test
void resolvesEachBatchTableWithItsOwnSchema() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
@@ -8,6 +8,8 @@ import io.github.hectorvent.floci.services.dynamodb.model.LocalSecondaryIndex;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
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 java.util.List;
@@ -21,6 +23,89 @@ class DynamoDbConditionKeysTest {
private final ObjectMapper mapper = new ObjectMapper();
private TableDefinition table;
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"SELECT payload FROM FgacTable | payload",
"SELECT PK FROM FgacTable WHERE payload = 'secret' | PK,payload",
"SELECT document.child FROM FgacTable WHERE NOT (hidden[0] = 1 OR PK = 'x') | document,hidden,PK",
"SELECT PK FROM FgacTable WHERE size(payload) > 1 | PK,payload",
"SELECT PK FROM FgacTable ORDER BY sortKey | PK,sortKey",
"SELECT PK FROM FgacTable WHERE PK = ? | PK"
})
void partiqlAttributesIncludeSelectedAndPredicatePaths(String statement, String expected) {
JsonNode body = mapper.createObjectNode().put("Statement", statement)
.set("Parameters", statement.contains("?") ? json("[{\"S\":\"one\"}]") : json("[]"));
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract("dynamodb:PartiQLSelect", body, table);
assertEquals(List.of(expected.split(",")), result.attributes());
assertEquals("SPECIFIC_ATTRIBUTES", result.select());
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"GetItem | {} | ALL_ATTRIBUTES",
"GetItem | {\"ProjectionExpression\":\"PK\"} | SPECIFIC_ATTRIBUTES",
"BatchGetItem | {\"RequestItems\":{\"FgacTable\":{\"Keys\":[]}}} | ALL_ATTRIBUTES",
"BatchGetItem | {\"RequestItems\":{\"FgacTable\":{\"Keys\":[],\"AttributesToGet\":[\"PK\"]}}} | SPECIFIC_ATTRIBUTES",
"PartiQLSelect | {\"Statement\":\"SELECT * FROM FgacTable\"} | ALL_ATTRIBUTES",
"PartiQLSelect | {\"Statement\":\"SELECT PK FROM FgacTable\"} | SPECIFIC_ATTRIBUTES",
"Query | {} | ALL_ATTRIBUTES",
"Scan | {} | ALL_ATTRIBUTES",
"Query | {\"IndexName\":\"by-value\"} | ALL_PROJECTED_ATTRIBUTES",
"Scan | {\"IndexName\":\"by-value\"} | ALL_PROJECTED_ATTRIBUTES",
"Query | {\"ProjectionExpression\":\"PK\"} | SPECIFIC_ATTRIBUTES",
"Scan | {\"ProjectionExpression\":\"PK\"} | SPECIFIC_ATTRIBUTES",
"Query | {\"AttributesToGet\":[\"PK\"]} | SPECIFIC_ATTRIBUTES",
"Scan | {\"AttributesToGet\":[\"PK\"]} | SPECIFIC_ATTRIBUTES",
"Query | {\"Select\":\"COUNT\",\"ProjectionExpression\":\"PK\"} | COUNT",
"Scan | {\"Select\":\"ALL_ATTRIBUTES\",\"IndexName\":\"by-value\"} | ALL_ATTRIBUTES",
"Query | {\"Select\":\"invalid\"} | invalid"
})
void selectionDefaultsMatchTheReadShape(String action, String body, String expected) {
assertEquals(expected, DynamoDbConditionKeys.extract("dynamodb:" + action, json(body), table).select());
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"{} | ALL_ATTRIBUTES",
"{\"Count\":false} | ALL_ATTRIBUTES",
"{\"AttributesToGet\":[\"PK\"]} | SPECIFIC_ATTRIBUTES",
"{\"Count\":true} | COUNT",
"{\"Count\":true,\"AttributesToGet\":[\"PK\"]} | COUNT",
"{\"Select\":\"COUNT\",\"ProjectionExpression\":\"PK\",\"IndexName\":\"ignored\"} | ALL_ATTRIBUTES"
})
void legacySelectionUsesOnlyMembersForwardedByTheAdapter(String body, String expected) {
assertEquals(expected, DynamoDbConditionKeys.extractLegacy("dynamodb:Query", json(body), table).select());
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"Query | {\"ProjectionExpression\":\"\"} | ALL_ATTRIBUTES",
"Scan | {\"ProjectionExpression\":\" \"} | ALL_ATTRIBUTES",
"Query | {\"AttributesToGet\":[]} | ALL_ATTRIBUTES",
"Scan | {\"AttributesToGet\":[]} | ALL_ATTRIBUTES",
"Query | {\"ProjectionExpression\":null} | ALL_ATTRIBUTES",
"Scan | {\"AttributesToGet\":null} | ALL_ATTRIBUTES",
"Query | {\"IndexName\":\"by-value\",\"ProjectionExpression\":\"\"} | ALL_PROJECTED_ATTRIBUTES",
"Scan | {\"IndexName\":\"by-value\",\"AttributesToGet\":[]} | ALL_PROJECTED_ATTRIBUTES",
"Query | {\"ProjectionExpression\":\"PK\"} | SPECIFIC_ATTRIBUTES",
"Scan | {\"AttributesToGet\":[\"PK\"]} | SPECIFIC_ATTRIBUTES",
"Query | {\"Select\":\"COUNT\",\"AttributesToGet\":[]} | COUNT"
})
void emptyProjectionMembersRetainTheDefaultSelection(String action, String body, String expected) {
assertEquals(expected, DynamoDbConditionKeys.extract("dynamodb:" + action, json(body), table).select());
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"{\"AttributesToGet\":[]} | ALL_ATTRIBUTES",
"{\"AttributesToGet\":null} | ALL_ATTRIBUTES",
"{\"AttributesToGet\":[\"PK\"]} | SPECIFIC_ATTRIBUTES",
"{\"Count\":true,\"AttributesToGet\":[]} | COUNT"
})
void legacyEmptyProjectionDoesNotClaimSpecificAttributes(String body, String expected) {
assertEquals(expected, DynamoDbConditionKeys.extractLegacy("dynamodb:Query", json(body), table).select());
}
@BeforeEach
void setUp() {
table = new TableDefinition();
@@ -64,7 +149,7 @@ class DynamoDbConditionKeysTest {
assertEquals(List.of("USER_alice"), result.leadingKeys());
assertEquals(List.of("PK", "SK"), result.attributes());
assertNull(result.select());
assertEquals("ALL_ATTRIBUTES", result.select());
}
@Test
@@ -0,0 +1,454 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import io.github.hectorvent.floci.testing.SignedIamEnforcementProfile;
import io.github.hectorvent.floci.testing.SignedIamUsers;
import io.github.hectorvent.floci.testutil.AwsRequestSigner;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
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.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes;
import java.net.URI;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestProfile(SignedIamEnforcementProfile.class)
class DynamoDbEmptyProjectionIntegrationTest {
private static final ObjectMapper JSON = new ObjectMapper();
private static final ObjectMapper CBOR = new ObjectMapper(new CBORFactory());
private static final String POLICY = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":["dynamodb:Query","dynamodb:Scan"],"Resource":"*",
"Condition":{"StringEquals":{"dynamodb:Select":"SPECIFIC_ATTRIBUTES"}}}]}
""";
@TestHTTPResource
URI endpoint;
@ParameterizedTest
@CsvSource({
"Query,json,expression", "Query,json,blank", "Query,json,attributes",
"Scan,json,expression", "Scan,json,blank", "Scan,json,attributes",
"Query,cbor,expression", "Query,cbor,attributes", "Scan,cbor,expression", "Scan,cbor,attributes",
"Query,legacy,attributes"
})
void emptyProjectionCannotSatisfySpecificAttributesPolicy(String action, String protocol, String member) throws Exception {
String table = "empty-projection-" + UUID.randomUUID();
AwsRequestSigner root = AwsRequestSigner.signedAs("test", "test", "dynamodb");
createTable(table, root);
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "empty-projection-", "select", POLICY)) {
ObjectNode request = read(table, action, protocol);
if ("attributes".equals(member)) {
request.putArray("AttributesToGet");
} else {
request.put("ProjectionExpression", "blank".equals(member) ? " " : "");
}
JsonNode full = response(send(root, action, protocol, request), protocol,
"attributes".equals(member) ? 400 : 200);
if ("attributes".equals(member)) {
assertTrue(full.path("__type").asText().contains("ValidationException"));
} else {
assertEquals(1, full.path("Count").asInt());
assertEquals("protected", full.path("Items").get(0).path("payload").path("S").asText());
}
JsonNode denied = response(send(user.signer("dynamodb"), action, protocol, request), protocol, "cbor".equals(protocol) ? 403 : 400);
assertTrue(denied.path("__type").asText().contains("AccessDeniedException"));
if (!"attributes".equals(member)) {
request.put("Select", "SPECIFIC_ATTRIBUTES");
JsonNode invalid = response(send(user.signer("dynamodb"), action, protocol, request), protocol, 400);
assertTrue(invalid.path("__type").asText().contains("ValidationException"));
request.remove("Select");
}
if ("attributes".equals(member)) {
request.putArray("AttributesToGet").add("pk");
} else {
request.put("ProjectionExpression", "pk");
}
JsonNode projected = response(send(user.signer("dynamodb"), action, protocol, request), protocol, 200);
assertEquals("one", projected.path("Items").get(0).path("pk").path("S").asText());
assertFalse(projected.path("Items").get(0).has("payload"));
} finally {
response(send(root, "DeleteTable", "json", JSON.createObjectNode().put("TableName", table)), "json", 200);
}
}
@ParameterizedTest
@ValueSource(strings = {"Query", "Scan"})
void signedSdkReadsRequireAnEffectiveProjection(String action) throws Exception {
String table = "sdk-projection-" + UUID.randomUUID();
AwsRequestSigner root = AwsRequestSigner.signedAs("test", "test", "dynamodb");
createTable(table, root);
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "sdk-projection-", "select", POLICY);
DynamoDbClient client = DynamoDbClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create(user.accessKeyId(), user.secretAccessKey()))).build()) {
Map<String, AttributeValue> values = Map.of(":pk", AttributeValue.fromS("one"));
DynamoDbException denial = assertThrows(DynamoDbException.class, () -> {
if ("Query".equals(action)) {
client.query(b -> b.tableName(table).keyConditionExpression("pk = :pk")
.expressionAttributeValues(values));
} else {
client.scan(b -> b.tableName(table));
}
});
assertEquals("AccessDeniedException", denial.awsErrorDetails().errorCode());
DynamoDbException empty = assertThrows(DynamoDbException.class, () -> {
if ("Query".equals(action)) {
client.query(b -> b.tableName(table).keyConditionExpression("pk = :pk")
.expressionAttributeValues(values).projectionExpression(""));
} else {
client.scan(b -> b.tableName(table).projectionExpression(""));
}
});
assertEquals("AccessDeniedException", empty.awsErrorDetails().errorCode());
Map<String, AttributeValue> item = "Query".equals(action)
? client.query(b -> b.tableName(table).keyConditionExpression("pk = :pk")
.expressionAttributeValues(values).projectionExpression("pk")).items().getFirst()
: client.scan(b -> b.tableName(table).projectionExpression("pk")).items().getFirst();
assertEquals(Map.of("pk", AttributeValue.fromS("one")), item);
} finally {
response(send(root, "DeleteTable", "json", JSON.createObjectNode().put("TableName", table)), "json", 200);
}
}
@ParameterizedTest
@CsvSource({
"Query,json,KEYS_ONLY,GSI",
"Query,json,KEYS_ONLY,LSI",
"Query,json,INCLUDE,GSI",
"Query,json,INCLUDE,LSI",
"Query,cbor,KEYS_ONLY,GSI",
"Query,cbor,KEYS_ONLY,LSI",
"Query,cbor,INCLUDE,GSI",
"Query,cbor,INCLUDE,LSI",
"Scan,json,KEYS_ONLY,GSI",
"Scan,json,KEYS_ONLY,LSI",
"Scan,json,INCLUDE,GSI",
"Scan,json,INCLUDE,LSI",
"Scan,cbor,KEYS_ONLY,GSI",
"Scan,cbor,KEYS_ONLY,LSI",
"Scan,cbor,INCLUDE,GSI",
"Scan,cbor,INCLUDE,LSI"})
void blankIndexProjectionCannotExposeTableAttributes(String action, String protocol, String projection, String indexKind) throws Exception {
String table = "index-projection-" + UUID.randomUUID();
AwsRequestSigner root = AwsRequestSigner.signedAs("test", "test", "dynamodb");
createTable(table, root, projection, indexKind);
String policy = POLICY.replace("SPECIFIC_ATTRIBUTES", "ALL_PROJECTED_ATTRIBUTES");
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "index-projection-", "select", policy)) {
for (String expression : new String[] {null, "", " "}) {
ObjectNode request = read(table, action, protocol).put("IndexName", "by-sort");
if ("Query".equals(action) && "GSI".equals(indexKind)) {
request.set("KeyConditions", JSON.readTree("""
{"sk":{"ComparisonOperator":"EQ","AttributeValueList":[{"S":"sort"}]}}
"""));
}
if (expression != null) {
request.put("ProjectionExpression", expression);
}
JsonNode result = response(send(user.signer("dynamodb"), action, protocol, request), protocol, 200);
assertEquals(1, result.path("Count").asInt());
JsonNode item = result.path("Items").get(0);
assertEquals("one", item.path("pk").path("S").asText());
assertEquals("sort", item.path("sk").path("S").asText());
assertFalse(item.has("payload"), result.toString());
assertEquals("INCLUDE".equals(projection), item.has("visible"));
}
} finally {
response(send(root, "DeleteTable", "json", JSON.createObjectNode().put("TableName", table)), "json", 200);
}
}
@ParameterizedTest
@CsvSource({"GetItem,json", "GetItem,cbor", "BatchGetItem,json", "BatchGetItem,cbor",
"ExecuteStatement,json", "ExecuteStatement,cbor"})
void generatedSelectCoverageEnforcesOtherReadActions(String action, String protocol) throws Exception {
String table = "generated-select-" + UUID.randomUUID();
AwsRequestSigner root = AwsRequestSigner.signedAs("test", "test", "dynamodb");
createTable(table, root);
String policy = POLICY.replace("\"dynamodb:Query\",\"dynamodb:Scan\"",
"\"dynamodb:GetItem\",\"dynamodb:BatchGetItem\",\"dynamodb:PartiQLSelect\"");
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "generated-select-", "select", policy)) {
ObjectNode request = JSON.createObjectNode();
ObjectNode selection = request;
if ("ExecuteStatement".equals(action)) {
request.put("Statement", "SELECT * FROM \"" + table + "\"");
} else {
JsonNode key = JSON.readTree("""
{"pk":{"S":"one"},"sk":{"S":"sort"}}
""");
if ("BatchGetItem".equals(action)) {
selection = request.putObject("RequestItems").putObject(table);
selection.putArray("Keys").add(key);
} else {
request.put("TableName", table).set("Key", key);
}
}
JsonNode denied = response(send(user.signer("dynamodb"), action, protocol, request), protocol,
"cbor".equals(protocol) ? 403 : 400);
assertTrue(denied.path("__type").asText().contains("AccessDeniedException"));
if ("ExecuteStatement".equals(action)) {
request.put("Statement", "SELECT pk FROM \"" + table + "\"");
} else {
selection.put("ProjectionExpression", "pk");
}
JsonNode result = response(send(user.signer("dynamodb"), action, protocol, request), protocol, 200);
JsonNode item = "GetItem".equals(action) ? result.path("Item")
: "BatchGetItem".equals(action) ? result.path("Responses").path(table).get(0)
: result.path("Items").get(0);
assertEquals("one", item.path("pk").path("S").asText());
assertFalse(item.has("payload"), result.toString());
} finally {
response(send(root, "DeleteTable", "json", JSON.createObjectNode().put("TableName", table)), "json", 200);
}
}
@ParameterizedTest
@CsvSource({"GetItem,json", "GetItem,cbor", "BatchGetItem,json", "BatchGetItem,cbor"})
void emptyAttributeListHasValidationErrorWireShape(String action, String protocol) throws Exception {
String table = "empty-list-" + UUID.randomUUID();
AwsRequestSigner root = AwsRequestSigner.signedAs("test", "test", "dynamodb");
createTable(table, root);
try {
JsonNode key = JSON.readTree("""
{"pk":{"S":"one"},"sk":{"S":"sort"}}
""");
ObjectNode request = JSON.createObjectNode();
ObjectNode selection = request;
if ("BatchGetItem".equals(action)) {
selection = request.putObject("RequestItems").putObject(table);
selection.putArray("Keys").add(key);
} else {
request.put("TableName", table).set("Key", key);
}
selection.putArray("AttributesToGet");
JsonNode error = response(send(root, action, protocol, request), protocol, 400);
assertTrue(error.path("__type").asText().contains("ValidationException"), error.toString());
assertTrue(error.path("message").asText().contains("greater than or equal to 1"), error.toString());
assertTrue(error.path("message").asText().contains("Value '[]' at 'attributesToGet'"), error.toString());
} finally {
response(send(root, "DeleteTable", "json", JSON.createObjectNode().put("TableName", table)), "json", 200);
}
}
@ParameterizedTest
@ValueSource(strings = {"json", "cbor"})
void partiqlCannotReadOrFilterForbiddenAttributes(String protocol) throws Exception {
String table = "partiql-attributes-" + UUID.randomUUID();
AwsRequestSigner root = AwsRequestSigner.signedAs("test", "test", "dynamodb");
createTable(table, root);
String policy = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":"dynamodb:PartiQLSelect","Resource":"*","Condition":{
"StringEquals":{"dynamodb:Select":"SPECIFIC_ATTRIBUTES"},
"ForAllValues:StringEquals":{"dynamodb:Attributes":["pk"]}}}]}
""";
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "partiql-attributes-", "read", policy);
DynamoDbClient client = DynamoDbClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create(user.accessKeyId(), user.secretAccessKey()))).build()) {
for (String statement : List.of("SELECT payload FROM \"%s\"",
"SELECT pk FROM \"%s\" WHERE payload = 'protected'")) {
String sql = statement.formatted(table);
JsonNode denied = response(send(user.signer("dynamodb"), "ExecuteStatement", protocol,
JSON.createObjectNode().put("Statement", sql)), protocol, "cbor".equals(protocol) ? 403 : 400);
assertTrue(denied.path("__type").asText().contains("AccessDeniedException"));
DynamoDbException error = assertThrows(DynamoDbException.class,
() -> client.executeStatement(b -> b.statement(sql)));
assertEquals("AccessDeniedException", error.awsErrorDetails().errorCode());
}
String allowed = "SELECT pk FROM \"" + table + "\" WHERE pk = ?";
ObjectNode request = JSON.createObjectNode().put("Statement", allowed);
request.putArray("Parameters").addObject().put("S", "one");
JsonNode item = response(send(user.signer("dynamodb"), "ExecuteStatement", protocol, request),
protocol, 200).path("Items").get(0);
assertEquals(JSON.readTree("{\"pk\":{\"S\":\"one\"}}"), item);
assertEquals(Map.of("pk", AttributeValue.fromS("one")), client.executeStatement(b -> b.statement(allowed)
.parameters(AttributeValue.fromS("one"))).items().getFirst());
} finally {
response(send(root, "DeleteTable", "json", JSON.createObjectNode().put("TableName", table)), "json", 200);
}
}
@ParameterizedTest
@CsvSource({"json,false", "json,true", "cbor,false", "cbor,true"})
void batchAliasesCannotHideUnprojectedReads(String protocol, boolean arnFirst) throws Exception {
String table = "batch-alias-" + UUID.randomUUID();
AwsRequestSigner root = AwsRequestSigner.signedAs("test", "test", "dynamodb");
createTable(table, root);
String arn = response(send(root, "DescribeTable", "json", JSON.createObjectNode().put("TableName", table)),
"json", 200).path("Table").path("TableArn").asText();
String policy = POLICY.replace("\"dynamodb:Query\",\"dynamodb:Scan\"", "\"dynamodb:BatchGetItem\"");
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "batch-alias-", "read", policy);
DynamoDbClient client = DynamoDbClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create(user.accessKeyId(), user.secretAccessKey()))).build()) {
ObjectNode request = JSON.createObjectNode();
ObjectNode entries = request.putObject("RequestItems");
String first = arnFirst ? arn : table;
String second = arnFirst ? table : arn;
JsonNode key = JSON.readTree("{\"pk\":{\"S\":\"one\"},\"sk\":{\"S\":\"sort\"}}");
entries.putObject(first).put("ProjectionExpression", "pk").putArray("Keys").add(key);
ObjectNode unprojected = entries.putObject(second);
unprojected.putArray("Keys").add(key);
JsonNode rootRead = response(send(root, "BatchGetItem", protocol, request), protocol, 200);
assertEquals("protected", rootRead.path("Responses").path(second).get(0).path("payload").path("S").asText());
JsonNode denied = response(send(user.signer("dynamodb"), "BatchGetItem", protocol, request), protocol,
"cbor".equals(protocol) ? 403 : 400);
assertTrue(denied.path("__type").asText().contains("AccessDeniedException"));
Map<String, AttributeValue> sdkKey = Map.of("pk", AttributeValue.fromS("one"), "sk", AttributeValue.fromS("sort"));
Map<String, KeysAndAttributes> sdkEntries = new LinkedHashMap<>();
sdkEntries.put(first, KeysAndAttributes.builder().keys(sdkKey).projectionExpression("pk").build());
sdkEntries.put(second, KeysAndAttributes.builder().keys(sdkKey).build());
DynamoDbException error = assertThrows(DynamoDbException.class,
() -> client.batchGetItem(b -> b.requestItems(sdkEntries)));
assertEquals("AccessDeniedException", error.awsErrorDetails().errorCode());
unprojected.put("ProjectionExpression", "pk");
JsonNode allowed = response(send(user.signer("dynamodb"), "BatchGetItem", protocol, request), protocol, 200);
for (String reference : List.of(first, second)) {
assertEquals(JSON.readTree("{\"pk\":{\"S\":\"one\"}}"),
allowed.path("Responses").path(reference).get(0));
}
sdkEntries.put(second, KeysAndAttributes.builder().keys(sdkKey).projectionExpression("pk").build());
assertEquals(2, client.batchGetItem(b -> b.requestItems(sdkEntries)).responses().size());
} finally {
response(send(root, "DeleteTable", "json", JSON.createObjectNode().put("TableName", table)), "json", 200);
}
}
@ParameterizedTest
@ValueSource(strings = {"json", "cbor"})
void transactionSelectionIgnoresUnsupportedGetMembers(String protocol) throws Exception {
String table = "transaction-projection-" + UUID.randomUUID();
AwsRequestSigner root = AwsRequestSigner.signedAs("test", "test", "dynamodb");
createTable(table, root);
String policy = POLICY.replace("\"dynamodb:Query\",\"dynamodb:Scan\"", "\"dynamodb:GetItem\"");
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "transaction-projection-", "read", policy);
DynamoDbClient client = DynamoDbClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create(user.accessKeyId(), user.secretAccessKey()))).build()) {
ObjectNode request = JSON.createObjectNode();
ObjectNode get = request.putArray("TransactItems").addObject().putObject("Get").put("TableName", table);
get.set("Key", JSON.readTree("{\"pk\":{\"S\":\"one\"},\"sk\":{\"S\":\"sort\"}}"));
get.putArray("AttributesToGet").add("pk");
JsonNode full = response(send(root, "TransactGetItems", protocol, request), protocol, 200)
.path("Responses").get(0).path("Item");
assertEquals("protected", full.path("payload").path("S").asText());
JsonNode denied = response(send(user.signer("dynamodb"), "TransactGetItems", protocol, request),
protocol, "cbor".equals(protocol) ? 403 : 400);
assertTrue(denied.path("__type").asText().contains("AccessDeniedException"));
get.put("ProjectionExpression", "#key");
get.putObject("ExpressionAttributeNames").put("#key", "pk");
JsonNode projected = response(send(user.signer("dynamodb"), "TransactGetItems", protocol, request),
protocol, 200).path("Responses").get(0).path("Item");
assertEquals(JSON.readTree("{\"pk\":{\"S\":\"one\"}}"), projected);
Map<String, AttributeValue> key = Map.of("pk", AttributeValue.fromS("one"),
"sk", AttributeValue.fromS("sort"));
DynamoDbException error = assertThrows(DynamoDbException.class, () -> client.transactGetItems(b ->
b.transactItems(t -> t.get(g -> g.tableName(table).key(key)))));
assertEquals("AccessDeniedException", error.awsErrorDetails().errorCode());
assertEquals(Map.of("pk", AttributeValue.fromS("one")), client.transactGetItems(b ->
b.transactItems(t -> t.get(g -> g.tableName(table).key(key).projectionExpression("pk"))))
.responses().getFirst().item());
} finally {
response(send(root, "DeleteTable", "json", JSON.createObjectNode().put("TableName", table)), "json", 200);
}
}
private void createTable(String table, AwsRequestSigner root) throws Exception {
createTable(table, root, null, null);
}
private void createTable(String table, AwsRequestSigner root, String projection, String indexKind) throws Exception {
ObjectNode request = (ObjectNode) JSON.readTree("""
{"KeySchema":[{"AttributeName":"pk","KeyType":"HASH"},{"AttributeName":"sk","KeyType":"RANGE"}],
"AttributeDefinitions":[{"AttributeName":"pk","AttributeType":"S"},{"AttributeName":"sk","AttributeType":"S"}],
"BillingMode":"PAY_PER_REQUEST"}
""");
request.put("TableName", table);
if (projection != null) {
boolean local = "LSI".equals(indexKind);
ObjectNode index = request.putArray(local ? "LocalSecondaryIndexes" : "GlobalSecondaryIndexes")
.addObject().put("IndexName", "by-sort");
if (local) {
request.withArray("AttributeDefinitions").addObject().put("AttributeName", "idx").put("AttributeType", "S");
index.putArray("KeySchema").addObject().put("AttributeName", "pk").put("KeyType", "HASH");
index.withArray("KeySchema").addObject().put("AttributeName", "idx").put("KeyType", "RANGE");
} else {
index.putArray("KeySchema").addObject().put("AttributeName", "sk").put("KeyType", "HASH");
}
ObjectNode definition = index.putObject("Projection").put("ProjectionType", projection);
if ("INCLUDE".equals(projection)) {
definition.putArray("NonKeyAttributes").add("visible");
}
}
response(send(root, "CreateTable", "json", request), "json", 200);
try {
ObjectNode put = (ObjectNode) JSON.readTree("""
{"Item":{"pk":{"S":"one"},"sk":{"S":"sort"},"payload":{"S":"protected"},"visible":{"S":"public"},"idx":{"S":"local"}}}
""");
put.put("TableName", table);
response(send(root, "PutItem", "json", put), "json", 200);
} catch (Exception | AssertionError failure) {
try {
response(send(root, "DeleteTable", "json", JSON.createObjectNode().put("TableName", table)), "json", 200);
} catch (Exception | AssertionError cleanup) {
failure.addSuppressed(cleanup);
}
throw failure;
}
}
private ObjectNode read(String table, String action, String protocol) throws Exception {
ObjectNode request = JSON.createObjectNode().put("TableName", table);
if ("Query".equals(action)) {
if ("legacy".equals(protocol)) {
request.putObject("HashKeyValue").put("S", "one");
} else {
request.set("KeyConditions", JSON.readTree("""
{"pk":{"ComparisonOperator":"EQ","AttributeValueList":[{"S":"one"}]}}
"""));
}
}
return request;
}
private Response send(AwsRequestSigner signer, String action, String protocol, JsonNode request) throws Exception {
boolean cbor = "cbor".equals(protocol);
URI uri = cbor ? endpoint.resolve("/service/DynamoDB_20120810/operation/" + action) : endpoint;
String contentType = cbor ? "application/cbor" : "application/x-amz-json-1.0";
Map<String, String> headers = cbor ? Map.of("content-type", contentType, "accept", contentType)
: Map.of("content-type", contentType, "x-amz-target",
("legacy".equals(protocol) ? "DynamoDB_20111205." : "DynamoDB_20120810.") + action);
byte[] body = (cbor ? CBOR : JSON).writeValueAsBytes(request);
return given().filter(signer).headers(headers).body(body).post(uri);
}
private JsonNode response(Response response, String protocol, int status) throws Exception {
assertEquals(status, response.statusCode(), response.asString());
return ("cbor".equals(protocol) ? CBOR : JSON).readTree(response.asByteArray());
}
}
@@ -1,5 +1,8 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
@@ -16,6 +19,7 @@ import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* End-to-end proof of the scenario in issue #2926: one session scoped by
@@ -31,6 +35,83 @@ class DynamoDbFgacEnforcementIntegrationTest {
private static final String ROLE_ACCOUNT_ID = "222233334444";
private static final String REGION = "us-east-1";
@ParameterizedTest
@CsvSource({"Query,false", "Scan,false", "Query,true", "Scan,true"})
void defaultSelectionCannotBypassSpecificAttributesPolicy(String action, boolean index) {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String tableName = "fgac-select-" + suffix;
String roleName = "FgacSelect" + suffix;
createTableWithGsi(tableName, "by-value");
putItemWithGsiKey(tableName, "USER_alice", "group");
createRole(roleName);
putBroadDynamoDbRolePolicy(roleName);
String accessKey = assumeRoleWithSessionPolicy(roleName, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["dynamodb:Query","dynamodb:Scan"],"Resource":"*",
"Condition":{"StringEqualsIfExists":{"dynamodb:Select":"SPECIFIC_ATTRIBUTES"}}}]}
""");
String key = index ? "GSI_PK" : "PK";
String value = index ? "group" : "USER_alice";
String indexMember = index ? ",\"IndexName\":\"by-value\"" : "";
String keyMember = "Query".equals(action) ? """
,"KeyConditions":{"%s":{"ComparisonOperator":"EQ","AttributeValueList":[{"S":"%s"}]}}
""".formatted(key, value) : "";
String body = "{\"TableName\":\"" + tableName + "\"" + indexMember + keyMember;
given().header("Authorization", auth(accessKey, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20120810." + action).contentType(DYNAMODB_CONTENT_TYPE)
.body(body + "}").post("/").then().statusCode(400).body(containsString("AccessDeniedException"));
given().header("Authorization", auth(accessKey, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20120810." + action).contentType(DYNAMODB_CONTENT_TYPE)
.body(body + ",\"ProjectionExpression\":\"PK\"}").post("/").then().statusCode(200)
.body("Count", equalTo(1));
}
@ParameterizedTest
@ValueSource(strings = {"json", "cbor", "legacy"})
void defaultSelectionIsAvailableToExplicitAllowPoliciesAcrossProtocols(String protocol) throws Exception {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String tableName = "fgac-select-wire-" + suffix;
String roleName = "FgacSelectWire" + suffix;
given().header("Authorization", auth(ROLE_ACCOUNT_ID, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20120810.CreateTable").contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"TableName":"%s","KeySchema":[{"AttributeName":"PK","KeyType":"HASH"},
{"AttributeName":"SK","KeyType":"RANGE"}],
"AttributeDefinitions":[{"AttributeName":"PK","AttributeType":"S"},
{"AttributeName":"SK","AttributeType":"S"}],"BillingMode":"PAY_PER_REQUEST"}
""".formatted(tableName)).post("/").then().statusCode(200);
createRole(roleName);
putBroadDynamoDbRolePolicy(roleName);
String accessKey = assumeRoleWithSessionPolicy(roleName, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:Query","Resource":"*",
"Condition":{"StringEquals":{"dynamodb:Select":"ALL_ATTRIBUTES"}}}]}
""");
String body = "legacy".equals(protocol)
? """
{"TableName":"%s","HashKeyValue":{"S":"USER_alice"}}
""".formatted(tableName)
: """
{"TableName":"%s","KeyConditions":{"PK":{
"ComparisonOperator":"EQ","AttributeValueList":[{"S":"USER_alice"}]}}}
""".formatted(tableName);
if ("cbor".equals(protocol)) {
ObjectMapper cbor = new ObjectMapper(new CBORFactory());
JsonNode request = new ObjectMapper().readTree(body);
byte[] result = given().header("Authorization", auth(accessKey, "dynamodb"))
.contentType("application/cbor").accept("application/cbor")
.body(cbor.writeValueAsBytes(request)).post("/service/DynamoDB_20120810/operation/Query")
.then().statusCode(200).extract().asByteArray();
assertEquals(0, cbor.readTree(result).path("Count").asInt());
} else {
given().header("Authorization", auth(accessKey, "dynamodb"))
.header("X-Amz-Target", "legacy".equals(protocol)
? "DynamoDB_20111205.Query" : "DynamoDB_20120810.Query")
.contentType(DYNAMODB_CONTENT_TYPE).body(body).post("/").then().statusCode(200)
.body("Count", equalTo(0));
}
}
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();