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

+7 -2
View File
@@ -1,12 +1,12 @@
name: IAM Data Drift
# Checks the seven vendored files that come from AWS's live service reference rather than from a
# Checks the eight vendored files that come from AWS's live service reference rather than from a
# pinned dependency: the IAM service namespace list, the map of which resource each IAM action is
# authorized against, the map of operations AWS authorizes as an action of another name, the
# table of the operations that pass a role and the services they pass it to, the table of the
# operations that pass a Lambda network connector, the table of the
# tagging actions operations that tag what they create need, and the table of the resources each
# operation's request names. That
# operation's request names, and the DynamoDB condition key table. That
# needs the live service reference index, so unlike every other check here it can
# fail without anything in the repository having changed: an AWS outage, or a namespace AWS has
# retired. It therefore runs on its own, never as part of a job that ordinary changes trigger.
@@ -55,6 +55,11 @@ on:
- 'src/main/resources/aws/iam-request-resources.json'
- 'tools/aws/regen_iam_request_resources.py'
- 'tools/aws/test_regen_iam_request_resources.py'
- 'src/main/resources/aws/dynamodb-condition-keys.json'
- 'tools/aws/regen_dynamodb_condition_keys.py'
- 'tools/aws/test_regen_dynamodb_condition_keys.py'
- 'tools/aws/regen_partitions.py'
- 'tools/aws/regen_query_services.py'
- '.github/workflows/iam-data-drift.yml'
schedule:
# Mondays at 06:00 UTC, before the working week rather than during it.
+3
View File
@@ -100,6 +100,9 @@ jobs:
- name: Run generator tests
run: make aws-data-test
- name: Check DynamoDB condition request members
run: make dynamodb-condition-keys-check
- name: Check partitions.json against a fresh generation
run: make aws-data-check
+17 -2
View File
@@ -419,6 +419,9 @@ IAM_PASSED_NETWORK_CONNECTORS_PATHS := src/main/resources/aws/iam-passed-network
tools/aws/test_regen_iam_passed_network_connectors.py
IAM_TAG_ON_CREATE_PATHS := src/main/resources/aws/iam-tag-on-create.json tools/aws/regen_iam_tag_on_create.py \
$(IAM_PASSED_ROLES_GENERATOR) tools/aws/test_regen_iam_tag_on_create.py
DYNAMODB_CONDITION_KEYS_PATHS := src/main/resources/aws/dynamodb-condition-keys.json \
tools/aws/regen_dynamodb_condition_keys.py tools/aws/test_regen_dynamodb_condition_keys.py \
tools/aws/regen_partitions.py tools/aws/regen_query_services.py
IAM_REQUEST_RESOURCES_PATHS := src/main/resources/aws/iam-request-resources.json \
tools/aws/regen_iam_request_resources.py $(IAM_PASSED_ROLES_GENERATOR) \
tools/aws/test_regen_iam_request_resources.py
@@ -427,7 +430,7 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match A
@# Every check runs even when an earlier one fails, so one file's drift cannot hide another's
@# state. Sequential steps in CI stop at the first failure, which once left the action
@# resource gate unexercised while the namespace list was stale.
@namespaces=0; actions=0; authorized=0; passed=0; connectors=0; tagged=0; requested=0; \
@namespaces=0; actions=0; authorized=0; passed=0; connectors=0; tagged=0; requested=0; dynamodb=0; \
covers() { \
[ -z "$(strip $(CHANGED))" ] && return 0; \
for path in $(CHANGED); do case " $$1 " in *" $$path "*) return 0;; esac; done; \
@@ -455,8 +458,11 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match A
if covers "$(IAM_REQUEST_RESOURCES_PATHS)" "the table of the resources requests name"; then \
$(MAKE) --no-print-directory iam-request-resources-verify || requested=$$?; \
fi; \
if covers "$(DYNAMODB_CONDITION_KEYS_PATHS)" "the DynamoDB condition key table"; then \
$(MAKE) --no-print-directory dynamodb-condition-keys-verify || dynamodb=$$?; \
fi; \
if [ $$namespaces -ne 0 ] || [ $$actions -ne 0 ] || [ $$authorized -ne 0 ] || [ $$passed -ne 0 ] \
|| [ $$connectors -ne 0 ] || [ $$tagged -ne 0 ] || [ $$requested -ne 0 ]; then \
|| [ $$connectors -ne 0 ] || [ $$tagged -ne 0 ] || [ $$requested -ne 0 ] || [ $$dynamodb -ne 0 ]; then \
echo ""; \
echo "error: vendored IAM data does not match upstream:"; \
if [ $$namespaces -ne 0 ]; then \
@@ -480,6 +486,7 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match A
if [ $$requested -ne 0 ]; then \
echo " the table of the resources requests name, see its message above"; \
fi; \
if [ $$dynamodb -ne 0 ]; then echo " the DynamoDB condition key table"; fi; \
exit 1; \
fi
@@ -649,3 +656,11 @@ cfn-property-types-verify: ## CI gate (online): the vendored CloudFormation prop
cfn-property-types-test: ## Run the CloudFormation property type generator's unit tests
$(PYTHON) -m pytest tools/aws/test_regen_cfn_property_types.py -q
.PHONY: dynamodb-condition-keys-sync dynamodb-condition-keys-check dynamodb-condition-keys-verify
dynamodb-condition-keys-sync: ## Regenerate DynamoDB IAM condition keys from AWS and botocore
$(PYTHON) tools/aws/regen_dynamodb_condition_keys.py
dynamodb-condition-keys-check: ## Check DynamoDB condition request members against pinned botocore
$(PYTHON) tools/aws/regen_dynamodb_condition_keys.py --check
dynamodb-condition-keys-verify: ## Check DynamoDB condition action keys against AWS
$(PYTHON) tools/aws/regen_dynamodb_condition_keys.py --verify
@@ -0,0 +1,15 @@
# IAM-enabled compatibility cases
These cases require Floci with `floci.services.iam.enforcement-enabled=true` and
administrative test credentials. They are separate from the default `tests/`
suite, which runs with IAM enforcement disabled.
From `compatibility-tests/sdk-test-python`, run:
```sh
FLOCI_ENDPOINT=http://localhost:4566 pytest -q iam/test_dynamodb_select_defaults.py
```
The DynamoDB selection cases create disposable tables and roles, use scoped STS
sessions, and delete their resources in reverse dependency order. They verify
Query/Scan table and index defaults and explicit projection policies.
@@ -0,0 +1,94 @@
"""Query/Scan Select defaults with IAM enforcement enabled."""
from contextlib import ExitStack
import json
import boto3
import pytest
from botocore.exceptions import ClientError
@pytest.mark.parametrize("action", ["query", "scan"])
@pytest.mark.parametrize("index", [False, True])
def test_select_defaults_require_projection(
dynamodb_client, iam_client, sts_client, aws_config, unique_name, action, index
):
table = f"select-{unique_name}"
role_name = f"select-{unique_name}"
with ExitStack() as cleanup:
dynamodb_client.create_table(
TableName=table,
KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
AttributeDefinitions=[
{"AttributeName": "pk", "AttributeType": "S"},
{"AttributeName": "group_key", "AttributeType": "S"},
],
GlobalSecondaryIndexes=[{
"IndexName": "by-group",
"KeySchema": [{"AttributeName": "group_key", "KeyType": "HASH"}],
"Projection": {"ProjectionType": "KEYS_ONLY"},
}],
BillingMode="PAY_PER_REQUEST",
)
cleanup.callback(dynamodb_client.delete_table, TableName=table)
dynamodb_client.get_waiter("table_exists").wait(TableName=table)
dynamodb_client.put_item(TableName=table, Item={
"pk": {"S": "one"}, "group_key": {"S": "group"}, "extra": {"S": "visible"}
})
role = iam_client.create_role(
RoleName=role_name,
AssumeRolePolicyDocument=json.dumps({
"Version": "2012-10-17", "Statement": [{
"Effect": "Allow", "Principal": {"AWS": "*"}, "Action": "sts:AssumeRole"
}]
}),
)["Role"]
cleanup.callback(iam_client.delete_role, RoleName=role_name)
iam_client.put_role_policy(RoleName=role_name, PolicyName="read", PolicyDocument=json.dumps({
"Version": "2012-10-17", "Statement": [{
"Effect": "Allow", "Action": "dynamodb:*", "Resource": "*"
}]
}))
cleanup.callback(iam_client.delete_role_policy, RoleName=role_name, PolicyName="read")
def scoped_client(selection, operator):
credentials = sts_client.assume_role(
RoleArn=role["Arn"], RoleSessionName="select-test",
Policy=json.dumps({"Version": "2012-10-17", "Statement": [{
"Effect": "Allow", "Action": ["dynamodb:Query", "dynamodb:Scan"],
"Resource": "*", "Condition": {operator: {"dynamodb:Select": selection}}
}]}),
)["Credentials"]
client = boto3.client(
"dynamodb", endpoint_url=aws_config["endpoint_url"],
region_name=aws_config["region_name"],
aws_access_key_id=credentials["AccessKeyId"],
aws_secret_access_key=credentials["SecretAccessKey"],
aws_session_token=credentials["SessionToken"],
)
cleanup.callback(client.close)
return client
request = {"TableName": table}
if index:
request["IndexName"] = "by-group"
if action == "query":
request.update(
KeyConditionExpression="#key = :v",
ExpressionAttributeNames={"#key": "group_key" if index else "pk"},
ExpressionAttributeValues={":v": {"S": "group" if index else "one"}},
)
restricted = scoped_client("SPECIFIC_ATTRIBUTES", "StringEqualsIfExists")
with pytest.raises(ClientError) as error:
getattr(restricted, action)(**request)
assert error.value.response["Error"]["Code"] == "AccessDeniedException"
projected = getattr(restricted, action)(**request, ProjectionExpression="pk")
assert projected["Items"] == [{"pk": {"S": "one"}}]
allowed = scoped_client(
"ALL_PROJECTED_ATTRIBUTES" if index else "ALL_ATTRIBUTES", "StringEquals"
)
result = getattr(allowed, action)(**request)
expected = {"pk": {"S": "one"}, "group_key": {"S": "group"}}
if not index:
expected["extra"] = {"S": "visible"}
assert result["Items"] == [expected]
+14
View File
@@ -68,6 +68,20 @@ the AWS [2011-12-05 DescribeTable](https://docs.aws.amazon.com/amazondynamodb/la
and [BatchWriteItem](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/API_BatchWriteItem_v20111205.html)
documentation.
## Query and Scan IAM selection
With IAM enforcement enabled, `dynamodb:Select` includes the effective selection
for `Query` and `Scan`: `ALL_ATTRIBUTES` for an unprojected table read,
`ALL_PROJECTED_ATTRIBUTES` for an unprojected index read, and
`SPECIFIC_ATTRIBUTES` when a nonblank projection expression or a nonempty
attribute list is supplied. Blank expressions and empty lists retain the table or
index default for IAM evaluation. An explicit `Select` value
is preserved. Legacy Query uses `Count` and `AttributesToGet` for the same purpose.
`dynamodb:Attributes` still describes attributes named in the request, not all
attributes returned. An attributes-only condition does not require a projection;
use a `dynamodb:Select` condition when the policy must require specific attributes.
## Legacy conditional requests
The native backend accepts `KeyConditions` together with `FilterExpression`.
+3
View File
@@ -2354,6 +2354,9 @@ and requested attributes. `dynamodb:EnclosingOperation` identifies `TransactWrit
`TransactGetItems`; write items expose `ReturnValuesOnConditionCheckFailure` as
`dynamodb:ReturnValues` only when the request supplies a non-null value. An omitted value leaves
the condition key absent. Transaction API names alone do not grant item access.
Transaction reads derive selection and requested attributes from the transaction `Get` shape:
`ProjectionExpression`, its attribute-name aliases, and the key. Ignored `GetItem` fields such as
`AttributesToGet` cannot satisfy a projected-read policy on `TransactGetItems`.
Transaction item authorization uses the effective local table ARN, matching execution.
A permission on a foreign account table cannot grant access to a same-named local table.
+6
View File
@@ -330,6 +330,12 @@
</dependency>
<!-- Testing -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>dynamodb</artifactId>
<version>${aws.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>sagemaker</artifactId>
@@ -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);
File diff suppressed because it is too large. Load diff
@@ -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();
+107
View File
@@ -0,0 +1,107 @@
#!/usr/bin/env python3
"""Generate DynamoDB IAM condition action and request-member tables.
AWS Service Reference supplies every action's condition keys. Pinned botocore supplies
request paths; semantic condition keys (LeadingKeys, Attributes, Select) are derived
from the corresponding request members rather than a member named after the key.
--check re-derives members offline; --verify compares the complete action/key mapping
with AWS, including newly added keys. --source permits a saved reference document.
"""
from __future__ import annotations
import argparse
import json
import sys
import urllib.request
from pathlib import Path
from regen_partitions import resolve_botocore_data
from regen_query_services import latest_model_dir, load_model
OUTPUT = Path(__file__).resolve().parents[2] / "src/main/resources/aws/dynamodb-condition-keys.json"
URL = "https://servicereference.us-east-1.amazonaws.com/v1/dynamodb/dynamodb.json"
# These keys describe values derived from request structures, not scalar members.
DERIVED = {
"Attributes": {"Key", "Keys", "Item", "AttributesToGet", "ProjectionExpression",
"ExpressionAttributeNames", "KeyConditions", "QueryFilter", "ScanFilter",
"AttributeUpdates", "Expected", "KeyConditionExpression", "FilterExpression",
"ConditionExpression", "UpdateExpression", "Statement"},
"LeadingKeys": {"Key", "Keys", "Item", "KeyConditions", "KeyConditionExpression", "Statement"},
"Select": {"Select", "ProjectionExpression", "AttributesToGet", "IndexName", "Statement"},
"FullTableScan": {"Statement"},
}
def action_keys(reference):
resources = {r["Name"]: r.get("ConditionKeys", []) for r in reference["Resources"]}
return {"dynamodb:" + a["Name"]: sorted(set(a.get("ActionConditionKeys", [])) |
{k for r in a.get("Resources", [])
for k in r.get("ConditionKeys", resources.get(r["Name"], []))})
for a in sorted(reference["Actions"], key=lambda a: a["Name"])}
def member_paths(model, shape, names, prefix="", seen=frozenset()):
if shape in seen:
return []
seen = seen | {shape}
spec = model["shapes"][shape]
result = []
for name, member in sorted(spec.get("members", {}).items()):
path = prefix + name
if name in names:
result.append(path)
result.extend(member_paths(model, member["shape"], names, path + ".", seen))
for field in ("member", "value"):
if field in spec:
result.extend(member_paths(model, spec[field]["shape"], names, prefix + "*.", seen))
return sorted(set(result))
def request_members(model, keys):
result = {}
for operation, spec in sorted(model["operations"].items()):
if "input" not in spec:
continue
result[operation] = {key: member_paths(model, spec["input"]["shape"],
DERIVED.get(key.split(":", 1)[1], {key.split(":", 1)[1]}))
for key in sorted({k for values in keys.values() for k in values
if k.startswith("dynamodb:")})}
return result
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
parser.add_argument("--verify", action="store_true")
parser.add_argument("--source", type=Path)
parser.add_argument("--botocore-data", type=Path)
args = parser.parse_args(argv)
if args.check:
document = json.loads(OUTPUT.read_text())
model = load_model(latest_model_dir(resolve_botocore_data(args.botocore_data)[0], "dynamodb"))
expected = request_members(model, document["actions"])
if (document["members"] != expected
or document["attributesToGetMinimum"] != model["shapes"]["AttributeNameList"]["min"]):
raise ValueError("DynamoDB condition request members differ from pinned botocore")
else:
if args.source:
reference = json.loads(args.source.read_text())
else:
with urllib.request.urlopen(URL, timeout=30) as response:
reference = json.load(response)
keys = action_keys(reference)
if args.verify:
if json.loads(OUTPUT.read_text())["actions"] != keys:
raise ValueError("DynamoDB condition actions differ from AWS Service Reference")
else:
data, provenance = resolve_botocore_data(args.botocore_data)
model = load_model(latest_model_dir(data, "dynamodb"))
document = {"source": URL, "botocore": provenance, "actions": keys,
"members": request_members(model, keys),
"attributesToGetMinimum": model["shapes"]["AttributeNameList"]["min"]}
OUTPUT.write_text(json.dumps(document, indent=2) + "\n")
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,78 @@
"""Semantic mapping and recursive request-member coverage for DynamoDB IAM conditions."""
import json
import subprocess
import pytest
from regen_dynamodb_condition_keys import OUTPUT, action_keys, member_paths, request_members
def test_resource_and_action_keys_are_combined():
reference = {"Resources": [{"Name": "table", "ConditionKeys": ["aws:ResourceTag/${TagKey}"]}],
"Actions": [{"Name": "GetItem", "ActionConditionKeys": ["dynamodb:Select"],
"Resources": [{"Name": "table"}]}]}
assert action_keys(reference) == {"dynamodb:GetItem": ["aws:ResourceTag/${TagKey}", "dynamodb:Select"]}
def test_nested_batch_member_paths_and_recursive_shapes():
model = {"operations": {"BatchGetItem": {"input": {"shape": "Input"}}}, "shapes": {
"Input": {"members": {"RequestItems": {"shape": "Map"}}},
"Map": {"value": {"shape": "Request"}},
"Request": {"members": {"ProjectionExpression": {"shape": "String"},
"Recursive": {"shape": "Request"}}}, "String": {}}}
assert member_paths(model, "Input", {"ProjectionExpression"}) == ["RequestItems.*.ProjectionExpression"]
assert request_members(model, {"dynamodb:BatchGetItem": ["dynamodb:Select"]}) == {
"BatchGetItem": {"dynamodb:Select": ["RequestItems.*.ProjectionExpression"]}}
def test_all_five_select_actions_are_vendored():
document = json.loads(OUTPUT.read_text())
assert {action for action, keys in document["actions"].items() if "dynamodb:Select" in keys} == {
"dynamodb:GetItem", "dynamodb:BatchGetItem", "dynamodb:PartiQLSelect",
"dynamodb:Query", "dynamodb:Scan"}
assert "RequestItems.*.AttributesToGet" in document["members"]["BatchGetItem"]["dynamodb:Select"]
assert "Statement" in document["members"]["ExecuteStatement"]["dynamodb:Select"]
@pytest.mark.parametrize("changed", [
"src/main/resources/aws/dynamodb-condition-keys.json",
"tools/aws/regen_dynamodb_condition_keys.py",
"tools/aws/test_regen_dynamodb_condition_keys.py",
"tools/aws/regen_partitions.py",
"tools/aws/regen_query_services.py",
"",
])
def test_aggregate_gate_checks_condition_data_and_imports(tmp_path, changed):
result = run_aggregate_gate(tmp_path, changed, fail=True)
assert "checked:dynamodb-condition-keys-verify" in result.stdout
assert result.returncode != 0
assert "the DynamoDB condition key table" in result.stdout
@pytest.mark.parametrize("changed", [
"docs/services/dynamodb.md",
"src/main/resources/aws/iam-service-namespaces.json",
"src/main/resources/aws/dynamodb-condition-keys.json.bak",
])
def test_aggregate_gate_does_not_check_unrelated_condition_data(tmp_path, changed):
result = run_aggregate_gate(tmp_path, changed, fail=True)
assert "checked:dynamodb-condition-keys-verify" not in result.stdout
assert result.returncode == 0
def test_aggregate_gate_accepts_successful_condition_check(tmp_path):
result = run_aggregate_gate(tmp_path, "src/main/resources/aws/dynamodb-condition-keys.json", fail=False)
assert "checked:dynamodb-condition-keys-verify" in result.stdout
assert result.returncode == 0
def run_aggregate_gate(tmp_path, changed, fail):
recursive_make = tmp_path / "check-gate"
recursive_make.write_text(
'#!/bin/sh\nprintf "checked:%s\\n" "$2"\n'
+ ('[ "$2" != dynamodb-condition-keys-verify ]\n' if fail else 'exit 0\n'))
recursive_make.chmod(0o700)
return subprocess.run(
["make", "--no-print-directory", "iam-data-verify", "CHANGED=" + changed,
"MAKE=" + str(recursive_make)],
cwd=OUTPUT.parents[4], capture_output=True, text=True, check=False)