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

@@ -821,8 +821,10 @@ public class IamConditionContextResolver {
// Execution resolves ARN inputs within the request account; authorize that same table.
String executionTable = DynamoDbTableNames.resolveWithRegion(tableName, region).name();
String itemAction = "dynamodb:" + operation + "Item";
DynamoDbConditionKeys.Result keys = DynamoDbConditionKeys.extract(
itemAction, request, describeTargetTable(executionTable));
TableDefinition table = describeTargetTable(executionTable);
DynamoDbConditionKeys.Result keys = read
? DynamoDbConditionKeys.extractTransactionGet(request, table)
: DynamoDbConditionKeys.extract(itemAction, request, table);
Map<String, List<String>> context = new LinkedHashMap<>();
context.put("dynamodb:EnclosingOperation", List.of(read ? "TransactGetItems" : "TransactWriteItems"));
if (!keys.leadingKeys().isEmpty()) {
@@ -831,6 +833,9 @@ public class IamConditionContextResolver {
if (!keys.attributes().isEmpty()) {
context.put("dynamodb:Attributes", keys.attributes());
}
if (keys.select() != null) {
context.put("dynamodb:Select", List.of(keys.select()));
}
if (!read && request.hasNonNull("ReturnValuesOnConditionCheckFailure")) {
context.put("dynamodb:ReturnValues",
List.of(request.path("ReturnValuesOnConditionCheckFailure").asText()));
@@ -842,20 +847,32 @@ public class IamConditionContextResolver {
return checks;
}
/** Resolves each batch entry with its own schema, optionally restricted to one resource. */
/** Request-wide context for callers that do not yet have a resolved resource. */
Map<String, List<String>> dynamoDbBatchConditionContext(String action, ContainerRequestContext ctx,
String resourceArn) {
List<Map<String, List<String>>> entries = dynamoDbBatchConditionContexts(action, ctx, resourceArn);
if (entries == null) {
return null;
}
Map<String, List<String>> combined = new LinkedHashMap<>();
for (Map<String, List<String>> entry : entries) {
entry.forEach((key, values) -> combined.computeIfAbsent(key, ignored -> new ArrayList<>()).addAll(values));
}
return combined;
}
/** Each table reference retains its own scalar selection, even when name and ARN resolve alike. */
List<Map<String, List<String>>> dynamoDbBatchConditionContexts(String action, ContainerRequestContext ctx,
String resourceArn) {
if (!isDynamoDbBatch(action)) {
return null;
}
Map<String, List<String>> conditions = new LinkedHashMap<>();
List<Map<String, List<String>>> contexts = new ArrayList<>();
JsonNode body = bufferedJsonBody(ctx);
JsonNode items = body == null ? null : body.get("RequestItems");
if (items == null || !items.isObject()) {
return conditions;
return List.of(Map.of());
}
List<String> leadingKeys = new ArrayList<>();
Set<String> attributes = new LinkedHashSet<>();
items.properties().forEach(entry -> {
String reference = entry.getKey().trim();
if (resourceArn != null && !matchesTableResource(reference, resourceArn)) {
@@ -866,16 +883,19 @@ public class IamConditionContextResolver {
single.putObject("RequestItems").set(entry.getKey(), entry.getValue());
DynamoDbConditionKeys.Result keys = dynamoDbKeys(
action, single, describeTargetTable(reference), ctx);
leadingKeys.addAll(keys.leadingKeys());
attributes.addAll(keys.attributes());
Map<String, List<String>> conditions = new LinkedHashMap<>();
if (!keys.leadingKeys().isEmpty()) {
conditions.put("dynamodb:LeadingKeys", keys.leadingKeys());
}
if (!keys.attributes().isEmpty()) {
conditions.put("dynamodb:Attributes", keys.attributes());
}
if (keys.select() != null) {
conditions.put("dynamodb:Select", List.of(keys.select()));
}
contexts.add(conditions);
});
if (!leadingKeys.isEmpty()) {
conditions.put("dynamodb:LeadingKeys", List.copyOf(leadingKeys));
}
if (!attributes.isEmpty()) {
conditions.put("dynamodb:Attributes", List.copyOf(attributes));
}
return conditions;
return contexts.isEmpty() ? List.of(Map.of()) : contexts;
}
private static boolean isDynamoDbBatch(String action) {
@@ -1168,19 +1168,26 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
? ResourceAccountRelationship.SAME_ACCOUNT
: ResourceAccountRelationship.CROSS_ACCOUNT;
for (Map<String, List<String>> targetContext : targetContexts) {
Map<String, List<String>> effectiveContext = IamConditionContextResolver.withGlobalContext(
targetContext, resource, region, accountId, resourceOwnerAccountId);
if ("dynamodb".equals(credentialScope)) {
Map<String, List<String>> batchContext =
conditionContextResolver.dynamoDbBatchConditionContext(action, ctx, resource);
if (batchContext != null) {
effectiveContext.remove("dynamodb:LeadingKeys");
effectiveContext.remove("dynamodb:Attributes");
effectiveContext.remove("dynamodb:Select");
effectiveContext.putAll(batchContext);
List<Map<String, List<String>>> batchContexts = "dynamodb".equals(credentialScope)
? conditionContextResolver.dynamoDbBatchConditionContexts(action, ctx, resource) : null;
List<Map<String, List<String>>> resourceContexts = targetContexts;
if (batchContexts != null && !batchContexts.isEmpty()) {
resourceContexts = new ArrayList<>();
for (Map<String, List<String>> targetContext : targetContexts) {
for (Map<String, List<String>> batchContext : batchContexts) {
Map<String, List<String>> entryContext = targetContext == null
? new HashMap<>() : new HashMap<>(targetContext);
entryContext.remove("dynamodb:LeadingKeys");
entryContext.remove("dynamodb:Attributes");
entryContext.remove("dynamodb:Select");
entryContext.putAll(batchContext);
resourceContexts.add(entryContext);
}
}
}
for (Map<String, List<String>> targetContext : resourceContexts) {
Map<String, List<String>> effectiveContext = IamConditionContextResolver.withGlobalContext(
targetContext, resource, region, accountId, resourceOwnerAccountId);
ResourcePolicyDecision resourcePolicyDecision = evaluator.evaluateResourcePolicyFor(
effectiveResourcePolicies, principal, action, resource, effectiveContext);
Decision decision = evaluator.evaluateResolvedResourcePolicy(
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.AndExpr;
import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.BetweenExpr;
import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.CompareExpr;
@@ -57,6 +58,7 @@ final class DynamoDbAccessPathValidator {
static void validateSelection(String select, String indexName,
String projectionExpression, JsonNode attributesToGet) {
validateAttributesToGet(attributesToGet);
rejectWithSelect("ProjectionExpression", projectionExpression != null, select);
rejectWithSelect("AttributesToGet", attributesToGet != null, select);
if ("ALL_PROJECTED_ATTRIBUTES".equals(select) && indexName == null) {
@@ -65,6 +67,14 @@ final class DynamoDbAccessPathValidator {
}
}
static void validateAttributesToGet(JsonNode attributesToGet) {
int minimum = DynamoDbConditionKeyMembers.attributesToGetMinimum();
if (attributesToGet != null && attributesToGet.isArray() && attributesToGet.size() < minimum) {
throw validationException("1 validation error detected: " + SmithyValidationErrors.lengthTooShort(
"attributesToGet", attributesToGet.toString(), minimum));
}
}
static void validateGsiProjection(TableDefinition table, DynamoDbAccessPath accessPath,
String select, String projectionExpression,
JsonNode attributesToGet, JsonNode expressionAttributeNames) {
@@ -78,7 +88,7 @@ final class DynamoDbAccessPathValidator {
}
Set<String> requestedAttributes = new LinkedHashSet<>();
if (projectionExpression != null) {
if (ProjectionEvaluator.hasProjection(projectionExpression)) {
requestedAttributes.addAll(ProjectionEvaluator.topLevelAttributes(
projectionExpression, expressionAttributeNames));
}
@@ -0,0 +1,82 @@
package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.VendoredResources;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/** Action coverage from AWS Service Reference and request member paths from pinned botocore. */
final class DynamoDbConditionKeyMembers {
private static final JsonNode TABLE = VendoredResources.read("aws/dynamodb-condition-keys.json",
"DynamoDB IAM condition keys", input -> {
JsonNode document = new ObjectMapper().readTree(input);
if (!document.path("actions").isObject() || document.path("actions").isEmpty()
|| !document.path("members").isObject() || document.path("members").isEmpty()
|| document.path("attributesToGetMinimum").asInt() < 1) {
throw new IllegalStateException("Malformed DynamoDB IAM condition key table");
}
return document;
});
private DynamoDbConditionKeyMembers() {}
static int attributesToGetMinimum() {
return TABLE.path("attributesToGetMinimum").intValue();
}
static boolean supports(String action, String key) {
for (JsonNode condition : TABLE.path("actions").path(action == null ? "" : action)) {
if (key.equals(condition.asText())) {
return true;
}
}
return false;
}
static List<JsonNode> values(String operation, String key, String member, JsonNode body) {
List<JsonNode> values = new ArrayList<>();
for (JsonNode path : TABLE.path("members").path(operation).path(key)) {
String[] steps = path.asText().split("\\.");
if (member.equals(steps[steps.length - 1])) {
collect(body, steps, 0, values);
}
}
return values;
}
static JsonNode itemBody(String operation, String prefix, JsonNode body) {
if (body == null || !body.isObject()) {
return body;
}
Set<String> members = new LinkedHashSet<>();
for (JsonNode paths : TABLE.path("members").path(operation)) {
for (JsonNode path : paths) {
String value = path.asText();
if (value.startsWith(prefix)) {
members.add(value.substring(prefix.length()).split("\\.", 2)[0]);
}
}
}
ObjectNode item = body.deepCopy();
return item.retain(members);
}
private static void collect(JsonNode node, String[] steps, int position, List<JsonNode> values) {
if (node == null || node.isNull()) {
return;
}
if (position == steps.length) {
values.add(node);
} else if ("*".equals(steps[position])) {
node.forEach(child -> collect(child, steps, position + 1, values));
} else {
collect(node.get(steps[position]), steps, position + 1, values);
}
}
}
@@ -114,6 +114,7 @@ public final class DynamoDbConditionKeys {
}
}
addPartiQLAttributes(action, body, attributes);
addAttributesToGet(attributes, body.get("AttributesToGet"));
addProjectionAttributes(attributes, textOrNull(body.get("ProjectionExpression")),
body.get("ExpressionAttributeNames"));
@@ -134,8 +135,7 @@ public final class DynamoDbConditionKeys {
addAttributeNames(attributes, body.get("Expected"));
addAttributeNames(attributes, body.get("ScanFilter"));
return new Result(List.copyOf(leadingKeys), List.copyOf(attributes),
textOrNull(body.get("Select")));
return result(action, leadingKeys, attributes, effectiveSelect(action, body));
}
/** Condition keys for the separately routed 2011-12-05 JSON requests. */
@@ -171,9 +171,102 @@ public final class DynamoDbConditionKeys {
}
}
}
return new Result(List.copyOf(leadingKeys), List.copyOf(attributes),
"dynamodb:Query".equals(action) && body.path("Count").isBoolean()
&& body.path("Count").booleanValue() ? "COUNT" : null);
return result(action, leadingKeys, attributes, legacySelect(action, body));
}
private static Result result(String action, List<String> leadingKeys, Set<String> attributes, String select) {
return new Result(DynamoDbConditionKeyMembers.supports(action, "dynamodb:LeadingKeys")
? List.copyOf(leadingKeys) : List.of(),
DynamoDbConditionKeyMembers.supports(action, "dynamodb:Attributes")
? List.copyOf(attributes) : List.of(), select);
}
/** Transaction Get uses its modeled member paths while IAM authorizes the GetItem action. */
public static Result extractTransactionGet(JsonNode body, TableDefinition table) {
return extract("dynamodb:GetItem", DynamoDbConditionKeyMembers.itemBody(
"TransactGetItems", "TransactItems.*.Get.", body), table);
}
private static String effectiveSelect(String action, JsonNode body) {
if (!DynamoDbConditionKeyMembers.supports(action, "dynamodb:Select")) {
return null;
}
if ("dynamodb:PartiQLSelect".equals(action)) {
DynamoDbPartiQLParser.Stmt.Select select = partiQLSelect(body, "dynamodb:Select");
return select == null ? null : !select.columns().isEmpty() ? "SPECIFIC_ATTRIBUTES"
: select.index() == null ? "ALL_ATTRIBUTES" : "ALL_PROJECTED_ATTRIBUTES";
}
String operation = action.substring("dynamodb:".length());
for (JsonNode select : DynamoDbConditionKeyMembers.values(
operation, "dynamodb:Select", "Select", body)) {
String value = textOrNull(select);
if (value != null) {
return value;
}
}
for (JsonNode projection : DynamoDbConditionKeyMembers.values(
operation, "dynamodb:Select", "ProjectionExpression", body)) {
if (ProjectionEvaluator.hasProjection(textOrNull(projection))) {
return "SPECIFIC_ATTRIBUTES";
}
}
for (JsonNode attributes : DynamoDbConditionKeyMembers.values(
operation, "dynamodb:Select", "AttributesToGet", body)) {
if (attributes.isArray() && !attributes.isEmpty()) {
return "SPECIFIC_ATTRIBUTES";
}
}
return DynamoDbConditionKeyMembers.values(operation, "dynamodb:Select", "IndexName", body)
.stream().anyMatch(index -> textOrNull(index) != null)
? "ALL_PROJECTED_ATTRIBUTES" : "ALL_ATTRIBUTES";
}
private static void addPartiQLAttributes(String action, JsonNode body, Set<String> attributes) {
if (!"dynamodb:PartiQLSelect".equals(action)) {
return;
}
DynamoDbPartiQLParser.Stmt.Select select = partiQLSelect(body, "dynamodb:Attributes");
if (select != null) {
select.columns().forEach(path -> attributes.add(path.root()));
select.where().stream().flatMap(DynamoDbPartiQLParser::leaves)
.forEach(condition -> attributes.add(condition.path().root()));
select.orderBy().forEach(order -> attributes.add(order.attribute()));
}
}
private static DynamoDbPartiQLParser.Stmt.Select partiQLSelect(JsonNode body, String conditionKey) {
String statement = DynamoDbConditionKeyMembers.values(
"ExecuteStatement", conditionKey, "Statement", body).stream()
.map(DynamoDbConditionKeys::textOrNull).filter(value -> value != null).findFirst().orElse(null);
if (statement == null) {
return null;
}
try {
List<JsonNode> parameters = new ArrayList<>();
body.path("Parameters").forEach(parameters::add);
return DynamoDbPartiQLParser.parse(statement, parameters)
instanceof DynamoDbPartiQLParser.Stmt.Select select ? select : null;
} catch (RuntimeException ignored) {
// Execution reports an invalid statement; do not invent condition values.
return null;
}
}
private static String legacySelect(String action, JsonNode body) {
if (!"dynamodb:Query".equals(action)) {
return null;
}
if (body.path("Count").isBoolean() && body.path("Count").booleanValue()) {
return "COUNT";
}
// The legacy adapter only forwards AttributesToGet, not modern selection members.
return hasProjectedAttributes(body) ? "SPECIFIC_ATTRIBUTES" : "ALL_ATTRIBUTES";
}
private static boolean hasProjectedAttributes(JsonNode body) {
JsonNode attributes = body.get("AttributesToGet");
return attributes != null && attributes.isArray() && !attributes.isEmpty();
}
private static void addLegacyKey(List<String> leadingKeys, Set<String> attributes, JsonNode value, String name) {
@@ -191,7 +284,7 @@ public final class DynamoDbConditionKeys {
/**
* The extracted keys. {@code leadingKeys} holds partition-key values in request order
* (duplicates preserved), {@code attributes} holds attribute names in first-seen order
* with duplicates removed, {@code select} is the raw Select value or {@code null}.
* with duplicates removed, {@code select} includes Query/Scan defaults, and is otherwise the raw value or {@code null}.
*/
public record Result(List<String> leadingKeys, List<String> attributes, String select) {}
@@ -647,6 +647,7 @@ public class NativeDynamoDbJsonHandler {
? request.get("ExpressionAttributeNames") : null;
JsonNode attributesToGet = request.has("AttributesToGet") ? request.get("AttributesToGet") : null;
DynamoDbAccessPathValidator.validateAttributesToGet(attributesToGet);
if (attributesToGet != null && projectionExpression != null) {
throw new AwsException("ValidationException",
"Can not use both expression and non-expression parameters in the same request: "
@@ -1147,7 +1148,8 @@ public class NativeDynamoDbJsonHandler {
}
boolean hasAttributesToGet = attributesToGet != null && attributesToGet.size() > 0;
if ("SPECIFIC_ATTRIBUTES".equals(select) && projectionExpression == null && !hasAttributesToGet) {
if ("SPECIFIC_ATTRIBUTES".equals(select) && !ProjectionEvaluator.hasProjection(projectionExpression)
&& !hasAttributesToGet) {
throw SmithyValidationErrors.validationException(
SELECT_NEEDS_PROJECTION);
}
@@ -1185,7 +1187,7 @@ public class NativeDynamoDbJsonHandler {
.toList();
}
// Apply index projection (KEYS_ONLY / INCLUDE) when querying a secondary index
if (indexName != null && projectionExpression == null && attributesToGet == null) {
if (indexName != null && !ProjectionEvaluator.hasProjection(projectionExpression) && attributesToGet == null) {
queryItems = applyIndexProjection(queryItems, queryTable, queryAccessPath, select);
}
if (projectionExpression != null) {
@@ -1296,7 +1298,7 @@ public class NativeDynamoDbJsonHandler {
}
boolean hasAttributesToGetScan = attributesToGetScan != null && attributesToGetScan.size() > 0;
if ("SPECIFIC_ATTRIBUTES".equals(select)
&& projectionExpressionScan == null && !hasAttributesToGetScan) {
&& !ProjectionEvaluator.hasProjection(projectionExpressionScan) && !hasAttributesToGetScan) {
throw SmithyValidationErrors.validationException(
SELECT_NEEDS_PROJECTION);
}
@@ -1331,7 +1333,7 @@ public class NativeDynamoDbJsonHandler {
List<JsonNode> scanItems = result.items();
// Apply index projection (KEYS_ONLY / INCLUDE) when scanning a secondary index
if (indexNameScan != null && projectionExpressionScan == null && attributesToGetScan == null) {
if (indexNameScan != null && !ProjectionEvaluator.hasProjection(projectionExpressionScan) && attributesToGetScan == null) {
scanItems = applyIndexProjection(scanItems, scanTable, scanAccessPath, select);
}
if (projectionExpressionScan != null) {
@@ -1584,6 +1586,7 @@ public class NativeDynamoDbJsonHandler {
boolean usesAttributesToGet = false;
boolean usesProjectionExpression = false;
for (JsonNode tableRequest : items.values()) {
DynamoDbAccessPathValidator.validateAttributesToGet(tableRequest.get("AttributesToGet"));
usesAttributesToGet |= tableRequest.hasNonNull("AttributesToGet");
usesProjectionExpression |= tableRequest.hasNonNull("ProjectionExpression");
}
@@ -28,6 +28,10 @@ final class ProjectionEvaluator {
private ProjectionEvaluator() {}
static boolean hasProjection(String expression) {
return expression != null && !expression.isBlank();
}
/**
* Returns a new ObjectNode containing only the paths named in the expression.
* Resolves #alias references via exprAttrNames. Handles dot-path and [n] list index segments.
@@ -35,7 +39,7 @@ final class ProjectionEvaluator {
* compact to ascending source order, the way DynamoDB reconstructs projected items.
*/
static ObjectNode project(JsonNode item, String projectionExpression, JsonNode exprAttrNames) {
if (item == null || projectionExpression == null || projectionExpression.isBlank()) {
if (item == null || !hasProjection(projectionExpression)) {
return (ObjectNode) item;
}
validateExpression(projectionExpression, exprAttrNames);