feat(iam): support DynamoDB fine-grained access control (#2926) (#3011)

* refactor(iam): make the policy condition context multi-valued

Condition keys such as dynamodb:LeadingKeys and dynamodb:Attributes are set-typed by definition, but the evaluator carried the request context as Map<String,String> from the filter all the way into the condition block, so a set could not be represented at all.

Change the type to Map<String,List<String>> across evaluate, simulateCustomPolicy, simulatePrincipalPolicy and the condition helpers, and update the three in-tree call sites. Non-set operators keep today's semantics by comparing only the first value, which is behaviour-preserving for every key that is single-valued today. normalizeConditionContext now preserves an empty list, which the set operators need to distinguish an empty set from an absent key.

* feat(iam): support ForAllValues and ForAnyValue set operators

ForAllValues: and ForAnyValue: appeared nowhere in the IAM package, so
evaluateConditionBlock stripped only an IfExists suffix and the whole
prefixed string reached the operator switch as an unknown operator, which
yields false. Every policy scoping DynamoDB access through
ForAllValues:StringLike therefore denied the requests it was written to allow.

Parse the quantifier prefix ahead of the IfExists strip so
ForAnyValue:StringEqualsIfExists composes, and evaluate the quantifier over
the request's value list, reusing evaluateSingleCondition for each member so
every existing operator works under a quantifier with no new operator code.
Empty-set semantics follow AWS: ForAllValues matches vacuously, ForAnyValue
does not. An absent key still fails closed without IfExists.

* fix(iam): read every SimulatePrincipalPolicy context key value

extractContextEntries read only ContextKeyValues.member.1 and dropped the
rest, which was invisible while the condition context was single-valued but
silently breaks set operators: a ForAnyValue: condition satisfied by the
second supplied value evaluated as implicitDeny. Reuse extractIndexedValues
to collect the whole member list per context entry.

* feat(dynamodb): add a KeyConditionExpression partition-key value reader

IAM condition-key extraction needs the value a Query pins its partition key
to, which today only DynamoDbAccessPathValidator can compute and only as a
side effect of validation. Add a narrow package-internal reader over the
existing ExpressionEvaluator instead of widening the validator's visibility.
Anything it cannot resolve returns null, which the policy layer treats as an
unknown leading key and fails closed on.

* feat(dynamodb): extract LeadingKeys, Attributes and Select from a request

Add a static extractor covering GetItem, PutItem, UpdateItem, DeleteItem,
Query, BatchGetItem and BatchWriteItem. Partition-key values come from Key,
Item, the Query KeyConditionExpression or the per-table RequestItems entries;
attribute names come from Key/Item fields, AttributesToGet,
ProjectionExpression, UpdateExpression targets and ExpressionAttributeNames.

Whatever cannot be determined is absent rather than guessed, so an
unresolvable leading key yields an empty list and the policy layer fails
closed on it.

* feat(iam): populate the DynamoDB condition keys from the request

IamConditionContextResolver supplied s3:* keys only and returned null for every other service, so dynamodb:LeadingKeys, dynamodb:Attributes and dynamodb:Select were never in the request context and no DynamoDB fine-grained policy could match. Add a dynamodb branch that reads the body already buffered by ResourceArnBuilder, resolves the table's key schema through a lazily injected DynamoDbService, and emits the three keys.

A key that cannot be resolved is omitted rather than guessed, so a policy scoping access through it denies the request.

* test(iam): cover the DynamoDB LeadingKeys scenario end to end

Add the issue #2926 acceptance criteria at evaluator level, plus an HTTP test
with enforcement enabled where one scoped session reads USER_alice and is
denied USER_bob against the same table, and a request whose Key omits the
partition attribute is denied because its leading key cannot be proven.

* docs(iam): document the set operators and the DynamoDB condition keys

Record ForAllValues:/ForAnyValue: with their empty-set semantics, the three dynamodb:* condition keys and the actions they cover, and the fail-closed consequence for a request whose leading key cannot be determined.

* fix(iam): correct negated-operator, empty-set and locale handling in conditions

Three fail-open gaps in the condition evaluator, all more reachable now that the
set operators make multi-valued and negated conditions common:

- A negated operator (StringNotEquals, ArnNotLike, NotIpAddress, ...) against a
  condition that lists several values was ORed across them, so the value matched
  as long as it differed from any one entry. AWS ANDs the negated match across
  the list; a ForAllValues:StringNotEquals deny-list on dynamodb:Attributes now
  actually denies.
- Null treated a present-but-empty set as present, so the Null:{key:"false"}
  guard that policies pair with ForAllValues did not block the vacuous empty-set
  allow. An empty set now counts as absent for Null, matching AWS.
- The per-key lower-casing used the default locale while the context map is
  normalised with Locale.ROOT, so under a Turkish locale a key would never match
  its own Deny statement. Both sides now use Locale.ROOT.

* perf(iam): resolve the table key schema without the item-count scan

IamConditionContextResolver called DynamoDbService.describeTable on every
enforced DynamoDB request, and describeTable refreshes the table's item count
by calling size() on a ConcurrentSkipListMap ??? an O(items) traversal ??? before
the request is even authorized. The resolver only needs the HASH key name.

Add DynamoDbService.findTable, which returns the stored definition without the
count refresh, and switch the resolver to it. findTable returns Optional and
never throws, so the surrounding try/catch, its Logger and the now-unused
injected ObjectMapper go away.

* feat(dynamodb): widen condition attribute extraction and support legacy KeyConditions

dynamodb:Attributes under-reported: it collected item/key fields, AttributesToGet,
the projection and update expressions and ExpressionAttributeNames, but never the
names a FilterExpression, ConditionExpression or KeyConditionExpression references.
A Query projecting only allowed attributes while filtering on a forbidden one would
slip past a ForAllValues:StringEquals on dynamodb:Attributes. Walk the parsed
expression tree so literal names, not only #aliases, are captured.

A Query using the legacy KeyConditions map instead of KeyConditionExpression
produced no dynamodb:LeadingKeys at all. Read the EQ entry for the partition key
from that map as a fallback, and take attribute names from KeyConditions and
QueryFilter.

Also pins DynamoDbKeyConditionParser on begins_with (never an equality) and a
top-level OR (not constrained to one partition), both of which must yield null.

* docs(iam): note negated-operator, empty-set and widened Attributes semantics

Record that a negated condition operator ANDs across multiple policy values
(making ForAllValues:StringNotEquals a usable deny-list), that Null treats a
present-but-empty set as absent, and that dynamodb:Attributes now also reflects
filter / condition / key-condition expression names and the legacy KeyConditions
EQ entry.

* fix(dynamodb): replace em-dash with colon in DynamoDbConditionKeys

* fix(dynamodb): resolve GSI partition keys and capture UpdateExpression read attributes

* docs(dynamodb): clarify fail-closed Javadoc applies to LeadingKeys not Attributes
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-05 10:19:17 -04:00
1 parent d771783afb
commit 6653b9a4e4
16 files changed
+1950 -60

No files matched your search

+34 -4
View File
@@ -391,21 +391,49 @@ account key carries no identity policies of its own.
- `DateEquals`, `DateNotEquals`, `DateLessThan`, `DateGreaterThan` (and Equals variants)
- `Bool`, `IpAddress`, `NotIpAddress`, `Null`
- Supports `...IfExists` variants for all operators.
- Set operators `ForAllValues:` and `ForAnyValue:` over multi-valued condition keys, in AWS's
own spelling (the prefix match is case-sensitive). They compose with `IfExists`
(`ForAnyValue:StringEqualsIfExists`). `ForAllValues:` over an empty set matches vacuously
and `ForAnyValue:` over an empty set does not match, so pair `ForAllValues:` with
`"Null":{"<key>":"false"}` as you would on AWS: `Null` treats a present-but-empty set as
absent, so the guard fires either way.
- When a condition lists several values, a positive operator matches if the request value
equals **any** of them; a negated operator (`StringNotEquals`, `ArnNotLike`, `NotIpAddress`,
…) matches only if the request value differs from **all** of them. This is what makes
`ForAllValues:StringNotEquals` on `dynamodb:Attributes` a usable deny-list.
#### Condition keys floci populates
A `Condition` operator can only match a key floci actually places in the request context.
floci populates:
- `s3:prefix`, `s3:delimiter`, `s3:max-keys` — from the S3 request parameters.
- `aws:PrincipalArn` — the caller's ARN, resolved from the signing access key. It is the
- `s3:prefix`, `s3:delimiter`, `s3:max-keys`: from the S3 request parameters.
- `aws:PrincipalArn`: the caller's ARN, resolved from the signing access key. It is the
IAM-user ARN for a user access key, the assumed-role ARN for an STS session, and
`arn:aws:iam::<account>:root` for the bare account-id key (floci's account-root principal),
matching the ARN shape AWS itself reports for the account root. It is **absent** only for
unknown keys, where nothing about the caller can be resolved.
- `dynamodb:LeadingKeys`, `dynamodb:Attributes`, `dynamodb:Select`: from the DynamoDB request
body, for `GetItem`, `PutItem`, `UpdateItem`, `DeleteItem`, `Query`, `BatchGetItem` and
`BatchWriteItem` (`dynamodb:Select` for `Query` and `Scan`). `LeadingKeys` holds the
partition-key values the request names: from `Key`, `Item`, the `KeyConditionExpression`
equality, the legacy `KeyConditions` `EQ` entry, or each `RequestItems` entry. `Attributes`
holds the attribute names the request *names* (item and key fields, `AttributesToGet`,
projection / update / filter / condition / key-condition expressions, and
`ExpressionAttributeNames`); a request with no projection returns every attribute while
reporting only the names it mentions, exactly as on AWS, which is why AWS pairs `Attributes`
with `dynamodb:Select`. Each key is **omitted** when it cannot be determined (unknown table,
a `Key` that omits the partition attribute, an unparseable `KeyConditionExpression`, a
multi-table batch), so a policy scoping access through it denies the request rather than
allowing an unproven one.
**Consequence:** with enforcement on and access scoped purely through `dynamodb:LeadingKeys`,
a malformed request (such as a `GetItem` whose `Key` omits the partition attribute) is answered with
`AccessDeniedException` instead of the `ValidationException` DynamoDB would return. Failing
closed is the correct direction for a security boundary.
**Any other condition key is absent from the request context.** A plain (non-`IfExists`)
operator on an absent key makes the whole statement *not apply* — it neither matches nor
operator on an absent key makes the whole statement *not apply*: it neither matches nor
blocks. A `DenyRootUser`-style guardrail keyed on `aws:PrincipalArn` therefore fires against
the account root the same way it does on real AWS, consistent with the account root already
being bounded by SCPs (below): both forms of root enforcement now agree.
@@ -414,7 +442,9 @@ being bounded by SCPs (below): both forms of root enforcement now agree.
so `aws:PrincipalArn` for an assumed-role caller will not match a condition that pins a
different session name. This matches what `sts:GetCallerIdentity` already reports.
**Not yet supported**: `NotPrincipal`, resource-based policies (S3 bucket policy, Lambda resource policy).
**Not yet supported**: `NotPrincipal`, resource-based policies (S3 bucket policy, Lambda resource
policy), and `dynamodb:LeadingKeys` for `Scan`, `TransactWriteItems` / `TransactGetItems` and the
PartiQL operations.
### Assumed roles
@@ -1,42 +1,146 @@
package io.github.hectorvent.floci.core.common;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbConditionKeys;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.MultivaluedMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Builds the IAM request context: the condition keys a policy's Condition block can match,
* for the request currently being enforced.
*/
@ApplicationScoped
public class IamConditionContextResolver {
public Map<String, String> resolve(String credentialScope, String action, ContainerRequestContext ctx) {
/** Set by {@code ResourceArnBuilder.readJsonBody}, which runs earlier in the same filter pass. */
private static final String BUFFERED_JSON_BODY = "floci.bufferedJsonBody";
private final Instance<DynamoDbService> dynamoDbService;
private final RequestContext requestContext;
private final EmulatorConfig config;
@Inject
public IamConditionContextResolver(Instance<DynamoDbService> dynamoDbService,
RequestContext requestContext,
EmulatorConfig config) {
this.dynamoDbService = dynamoDbService;
this.requestContext = requestContext;
this.config = config;
}
public Map<String, List<String>> resolve(String credentialScope, String action,
ContainerRequestContext ctx) {
return switch (credentialScope) {
case "s3" -> s3ConditionContext(action, ctx);
case "dynamodb" -> dynamoDbConditionContext(action, ctx);
default -> null;
};
}
private Map<String, String> s3ConditionContext(String action, ContainerRequestContext ctx) {
// ── S3 ──────────────────────────────────────────────────────────────────────
private Map<String, List<String>> s3ConditionContext(String action, ContainerRequestContext ctx) {
return switch (action) {
case "s3:ListBucket" -> s3BucketListConditionContext(ctx.getUriInfo().getQueryParameters());
default -> null;
};
}
Map<String, String> s3BucketListConditionContext(MultivaluedMap<String, String> queryParameters) {
Map<String, String> conditions = new LinkedHashMap<>();
Map<String, List<String>> s3BucketListConditionContext(MultivaluedMap<String, String> queryParameters) {
Map<String, List<String>> conditions = new LinkedHashMap<>();
addQueryCondition(conditions, "s3:prefix", queryParameters, "prefix");
addQueryCondition(conditions, "s3:delimiter", queryParameters, "delimiter");
addQueryCondition(conditions, "s3:max-keys", queryParameters, "max-keys");
return conditions.isEmpty() ? null : conditions;
}
private static void addQueryCondition(Map<String, String> conditions, String conditionKey,
private static void addQueryCondition(Map<String, List<String>> conditions, String conditionKey,
MultivaluedMap<String, String> queryParameters, String queryParameter) {
String value = queryParameters.getFirst(queryParameter);
if (value != null) {
conditions.put(conditionKey, value);
conditions.put(conditionKey, List.of(value));
}
}
// ── DynamoDB ────────────────────────────────────────────────────────────────
/**
* Populates {@code dynamodb:LeadingKeys}, {@code dynamodb:Attributes} and
* {@code dynamodb:Select} from the buffered request body.
*
* <p>A key that cannot be resolved (unknown table, a Key that omits the partition
* attribute, an unparseable KeyConditionExpression) is omitted rather than guessed. A
* policy scoping access through the missing key then does not match, so the request is
* denied: a request that cannot be proven in scope is treated as out of scope.
*/
Map<String, List<String>> dynamoDbConditionContext(String action, ContainerRequestContext ctx) {
JsonNode body = bufferedJsonBody(ctx);
if (body == null || !body.isObject()) {
return null;
}
TableDefinition table = describeTargetTable(body);
DynamoDbConditionKeys.Result keys = DynamoDbConditionKeys.extract(action, body, table);
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()));
}
return conditions.isEmpty() ? null : conditions;
}
private JsonNode bufferedJsonBody(ContainerRequestContext ctx) {
Object cached = ctx.getProperty(BUFFERED_JSON_BODY);
return cached instanceof JsonNode node ? node : null;
}
/**
* Looks up the table whose key schema names the partition key. Resolved lazily through
* Instance so core.common keeps no hard dependency on the DynamoDB service, and via
* {@code findTable} rather than {@code describeTable} so the O(items) item-count refresh
* never runs on the enforcement hot path.
*/
private TableDefinition describeTargetTable(JsonNode body) {
String tableName = targetTableName(body);
if (tableName == null || !dynamoDbService.isResolvable()) {
return null;
}
String region = requestContext.getRegion() == null
? config.defaultRegion() : requestContext.getRegion();
return dynamoDbService.get().findTable(tableName, region).orElse(null);
}
/**
* The single table this request targets: the TableName field, or the sole RequestItems
* entry for the batch operations. A multi-table batch has no single key schema, so it
* gets no leading keys and fails closed.
*/
private String targetTableName(JsonNode body) {
if (body.hasNonNull("TableName")) {
String tableName = body.get("TableName").asText().trim();
if (!tableName.isEmpty()) {
return tableName;
}
}
JsonNode requestItems = body.get("RequestItems");
if (requestItems != null && requestItems.isObject() && requestItems.size() == 1) {
return requestItems.fieldNames().next();
}
return null;
}
}
@@ -171,7 +171,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
List<String> resources = arnBuilder.buildResources(credentialScope, ctx, region, accountId);
Map<String, String> conditionContext = conditionContextResolver.resolve(credentialScope, action, ctx);
Map<String, List<String>> conditionContext = conditionContextResolver.resolve(credentialScope, action, ctx);
// aws:PrincipalArn is populated for every principal this filter can identify — IAM users,
// assumed-role sessions, and now the synthesized account-root principal above, using AWS's
@@ -184,7 +184,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
: iamService.resolveCallerArn(akid);
if (principalArn.isPresent()) {
conditionContext = conditionContext == null ? new HashMap<>() : new HashMap<>(conditionContext);
conditionContext.put("aws:PrincipalArn", principalArn.get());
conditionContext.put("aws:PrincipalArn", List.of(principalArn.get()));
}
for (String resource : resources) {
@@ -0,0 +1,397 @@
package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex;
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
import io.github.hectorvent.floci.services.dynamodb.model.LocalSecondaryIndex;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Extracts the DynamoDB IAM condition keys - {@code dynamodb:LeadingKeys},
* {@code dynamodb:Attributes} and {@code dynamodb:Select} - from a request body.
*
* <p>Public and static, following the precedent of {@link DynamoDbPartiQLParser}, which the
* IAM package already calls across the package boundary.
*
* <p>Everything is best effort. Whatever cannot be determined is simply absent from the
* result: an unresolvable leading key produces an empty list, the condition key is then
* omitted from the request context, and a policy that scopes access through it fails closed.
* Note that this "fail closed" behavior applies to {@code dynamodb:LeadingKeys}; for
* {@code dynamodb:Attributes} evaluated under {@code ForAllValues}, under-reporting is the
* unsafe direction because omitting a referenced attribute could allow an unauthorized
* operation to pass.
*/
public final class DynamoDbConditionKeys {
private DynamoDbConditionKeys() {}
/**
* @param action the IAM action, e.g. {@code dynamodb:GetItem}
* @param body the parsed request body; may be {@code null}
* @param table the target table's definition, used only for the HASH key name; may be
* {@code null}, in which case no leading keys are produced
*/
public static Result extract(String action, JsonNode body, TableDefinition table) {
if (body == null || !body.isObject()) {
return new Result(List.of(), List.of(), null);
}
String pkName = partitionKeyName(table);
List<String> leadingKeys = new ArrayList<>();
Set<String> attributes = new LinkedHashSet<>();
switch (action == null ? "" : action) {
case "dynamodb:GetItem", "dynamodb:DeleteItem", "dynamodb:UpdateItem" -> {
JsonNode key = body.get("Key");
addAttributeNames(attributes, key);
addLeadingKey(leadingKeys, key, pkName);
}
case "dynamodb:PutItem" -> {
JsonNode item = body.get("Item");
addAttributeNames(attributes, item);
addLeadingKey(leadingKeys, item, pkName);
}
case "dynamodb:Query" -> {
String indexName = textOrNull(body.get("IndexName"));
String queryPkName = partitionKeyName(table, indexName);
String value = DynamoDbKeyConditionParser.partitionKeyEqualityValue(
textOrNull(body.get("KeyConditionExpression")),
body.get("ExpressionAttributeNames"),
body.get("ExpressionAttributeValues"),
queryPkName);
if (value == null) {
value = legacyKeyConditionEqualityValue(body.get("KeyConditions"), queryPkName);
}
if (value != null) {
leadingKeys.add(value);
}
// Legacy map forms of the same clauses; the expression forms are covered below.
addAttributeNames(attributes, body.get("KeyConditions"));
addAttributeNames(attributes, body.get("QueryFilter"));
}
case "dynamodb:BatchGetItem" -> {
for (JsonNode tableRequest : requestItemsFor(body, table)) {
JsonNode keys = tableRequest.get("Keys");
if (keys != null && keys.isArray()) {
for (JsonNode key : keys) {
addAttributeNames(attributes, key);
addLeadingKey(leadingKeys, key, pkName);
}
}
addAttributesToGet(attributes, tableRequest.get("AttributesToGet"));
addProjectionAttributes(attributes,
textOrNull(tableRequest.get("ProjectionExpression")),
tableRequest.get("ExpressionAttributeNames"));
}
}
case "dynamodb:BatchWriteItem" -> {
for (JsonNode tableRequest : requestItemsFor(body, table)) {
if (!tableRequest.isArray()) {
continue;
}
for (JsonNode write : tableRequest) {
JsonNode put = write.path("PutRequest").get("Item");
addAttributeNames(attributes, put);
addLeadingKey(leadingKeys, put, pkName);
JsonNode delete = write.path("DeleteRequest").get("Key");
addAttributeNames(attributes, delete);
addLeadingKey(leadingKeys, delete, pkName);
}
}
}
default -> {
// Scan and everything else: no leading keys. Attributes and Select below
// still apply where the body carries them.
}
}
addAttributesToGet(attributes, body.get("AttributesToGet"));
addProjectionAttributes(attributes, textOrNull(body.get("ProjectionExpression")),
body.get("ExpressionAttributeNames"));
addUpdateExpressionAttributes(attributes, textOrNull(body.get("UpdateExpression")),
body.get("ExpressionAttributeNames"));
addExpressionAttributeNameValues(attributes, body.get("ExpressionAttributeNames"));
// Names an expression references are attributes the request touches too. Under-reporting
// these is the unsafe direction: a Query projecting only allowed attributes but filtering
// on a forbidden one would still slip past a ForAllValues:StringEquals on dynamodb:Attributes.
JsonNode exprAttrNames = body.get("ExpressionAttributeNames");
addExpressionAttributes(attributes, textOrNull(body.get("KeyConditionExpression")), exprAttrNames);
addExpressionAttributes(attributes, textOrNull(body.get("FilterExpression")), exprAttrNames);
addExpressionAttributes(attributes, textOrNull(body.get("ConditionExpression")), exprAttrNames);
// Legacy map forms naming attributes being read or updated.
addAttributeNames(attributes, body.get("AttributeUpdates"));
addAttributeNames(attributes, body.get("Expected"));
addAttributeNames(attributes, body.get("ScanFilter"));
return new Result(List.copyOf(leadingKeys), List.copyOf(attributes),
textOrNull(body.get("Select")));
}
/**
* 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}.
*/
public record Result(List<String> leadingKeys, List<String> attributes, String select) {}
// -- Helpers -----------------------------------------------------------------
private static String partitionKeyName(TableDefinition table) {
return partitionKeyName(table, null);
}
private static String partitionKeyName(TableDefinition table, String indexName) {
if (table == null) {
return null;
}
if (indexName != null) {
if (table.getGlobalSecondaryIndexes() != null) {
for (GlobalSecondaryIndex gsi : table.getGlobalSecondaryIndexes()) {
if (indexName.equals(gsi.getIndexName())) {
return hashKeyName(gsi.getKeySchema());
}
}
}
if (table.getLocalSecondaryIndexes() != null) {
for (LocalSecondaryIndex lsi : table.getLocalSecondaryIndexes()) {
if (indexName.equals(lsi.getIndexName())) {
return hashKeyName(lsi.getKeySchema());
}
}
}
}
return hashKeyName(table.getKeySchema());
}
private static String hashKeyName(List<KeySchemaElement> schema) {
if (schema == null) {
return null;
}
return schema.stream()
.filter(key -> "HASH".equals(key.getKeyType()))
.map(KeySchemaElement::getAttributeName)
.findFirst()
.orElse(null);
}
/**
* The RequestItems entries this request touches. Prefers the entry named by the resolved
* table, because only that table's HASH key name is known; falls back to every entry when
* nothing matches, so a stub or an aliased name still yields something.
*/
private static List<JsonNode> requestItemsFor(JsonNode body, TableDefinition table) {
JsonNode requestItems = body.get("RequestItems");
if (requestItems == null || !requestItems.isObject()) {
return List.of();
}
String tableName = table == null ? null : table.getTableName();
if (tableName != null && requestItems.has(tableName)) {
return List.of(requestItems.get(tableName));
}
List<JsonNode> all = new ArrayList<>();
requestItems.elements().forEachRemaining(all::add);
return all;
}
private static void addLeadingKey(List<String> leadingKeys, JsonNode attributeMap, String pkName) {
if (attributeMap == null || !attributeMap.isObject() || pkName == null) {
return;
}
String value = scalarValue(attributeMap.get(pkName));
if (value != null) {
leadingKeys.add(value);
}
}
private static void addAttributeNames(Set<String> attributes, JsonNode attributeMap) {
if (attributeMap == null || !attributeMap.isObject()) {
return;
}
Iterator<String> names = attributeMap.fieldNames();
while (names.hasNext()) {
attributes.add(names.next());
}
}
private static void addAttributesToGet(Set<String> attributes, JsonNode attributesToGet) {
if (attributesToGet == null || !attributesToGet.isArray()) {
return;
}
for (JsonNode attribute : attributesToGet) {
if (attribute.isTextual()) {
attributes.add(attribute.asText());
}
}
}
private static void addProjectionAttributes(Set<String> attributes, String projectionExpression,
JsonNode exprAttrNames) {
if (projectionExpression == null || projectionExpression.isBlank()) {
return;
}
try {
attributes.addAll(ProjectionEvaluator.topLevelAttributes(projectionExpression, exprAttrNames));
} catch (RuntimeException e) {
// A malformed projection is the request handler's problem to report; for condition
// keys it just means those attribute names stay unknown.
}
}
private static void addExpressionAttributeNameValues(Set<String> attributes, JsonNode exprAttrNames) {
if (exprAttrNames == null || !exprAttrNames.isObject()) {
return;
}
exprAttrNames.elements().forEachRemaining(value -> {
if (value.isTextual()) {
attributes.add(value.asText());
}
});
}
private static final Set<String> UPDATE_EXPRESSION_KEYWORDS = Set.of(
"set", "remove", "add", "delete", "if_not_exists", "list_append"
);
private static final Pattern UPDATE_EXPRESSION_ATTRIBUTE_PATTERN =
Pattern.compile("(?<![.#a-zA-Z0-9_:'\"])(#?[a-zA-Z_][a-zA-Z0-9_]*)");
/**
* Top-level attribute names an UpdateExpression reads or writes. Captures LHS targets of
* SET/REMOVE/ADD/DELETE and RHS operands (such as attributes in arithmetic, list_append,
* or if_not_exists).
*/
private static void addUpdateExpressionAttributes(Set<String> attributes, String updateExpression,
JsonNode exprAttrNames) {
if (updateExpression == null || updateExpression.isBlank()) {
return;
}
Matcher matcher = UPDATE_EXPRESSION_ATTRIBUTE_PATTERN.matcher(updateExpression);
while (matcher.find()) {
String token = matcher.group(1);
if (UPDATE_EXPRESSION_KEYWORDS.contains(token.toLowerCase(Locale.ROOT))) {
continue;
}
String resolved = resolveAlias(token, exprAttrNames);
if (resolved != null && !resolved.startsWith("#")) {
attributes.add(resolved);
}
}
}
/** The EQ value a legacy {@code KeyConditions} map pins the partition key to, or {@code null}. */
private static String legacyKeyConditionEqualityValue(JsonNode keyConditions, String pkName) {
if (keyConditions == null || !keyConditions.isObject() || pkName == null) {
return null;
}
JsonNode condition = keyConditions.get(pkName);
if (condition == null || !"EQ".equals(textOrNull(condition.get("ComparisonOperator")))) {
return null;
}
JsonNode list = condition.get("AttributeValueList");
if (list == null || !list.isArray() || list.isEmpty()) {
return null;
}
return scalarValue(list.get(0));
}
/**
* Top-level attribute names a DynamoDB expression references: a FilterExpression,
* ConditionExpression or KeyConditionExpression. Walks the parsed tree so a literal name
* such as {@code ssn} in {@code "ssn = :x"} is captured, not only {@code #alias}es.
* A malformed expression yields nothing, which only ever denies.
*/
private static void addExpressionAttributes(Set<String> attributes, String expression,
JsonNode exprAttrNames) {
if (expression == null || expression.isBlank()) {
return;
}
ExpressionEvaluator.Expr root;
try {
root = ExpressionEvaluator.parse(expression);
} catch (RuntimeException e) {
return;
}
collectExpressionPaths(root, attributes, exprAttrNames);
}
private static void collectExpressionPaths(ExpressionEvaluator.Expr expr, Set<String> attributes,
JsonNode exprAttrNames) {
if (expr == null) {
return;
}
switch (expr) {
case ExpressionEvaluator.AndExpr and ->
and.operands().forEach(o -> collectExpressionPaths(o, attributes, exprAttrNames));
case ExpressionEvaluator.OrExpr or ->
or.operands().forEach(o -> collectExpressionPaths(o, attributes, exprAttrNames));
case ExpressionEvaluator.NotExpr not ->
collectExpressionPaths(not.operand(), attributes, exprAttrNames);
case ExpressionEvaluator.CompareExpr cmp -> {
collectOperandPath(cmp.left(), attributes, exprAttrNames);
collectOperandPath(cmp.right(), attributes, exprAttrNames);
}
case ExpressionEvaluator.BetweenExpr between -> {
collectOperandPath(between.value(), attributes, exprAttrNames);
collectOperandPath(between.low(), attributes, exprAttrNames);
collectOperandPath(between.high(), attributes, exprAttrNames);
}
case ExpressionEvaluator.InExpr in -> {
collectOperandPath(in.value(), attributes, exprAttrNames);
in.candidates().forEach(c -> collectOperandPath(c, attributes, exprAttrNames));
}
case ExpressionEvaluator.FunctionCallExpr fn ->
fn.args().forEach(a -> collectOperandPath(a, attributes, exprAttrNames));
default -> { }
}
}
private static void collectOperandPath(ExpressionEvaluator.Operand operand, Set<String> attributes,
JsonNode exprAttrNames) {
if (operand instanceof ExpressionEvaluator.PathOperand path && !path.segments().isEmpty()) {
String name = resolveAlias(path.segments().getFirst(), exprAttrNames);
if (name != null && !name.startsWith(":")) {
attributes.add(name);
}
} else if (operand instanceof ExpressionEvaluator.FunctionOperand fn) {
fn.args().forEach(a -> collectOperandPath(a, attributes, exprAttrNames));
}
}
private static String resolveAlias(String segment, JsonNode exprAttrNames) {
if (segment.startsWith("#") && exprAttrNames != null && exprAttrNames.has(segment)) {
return exprAttrNames.get(segment).asText();
}
return segment;
}
/** Unwraps an AttributeValue to its scalar text. Only S, N and B can be key values. */
private static String scalarValue(JsonNode attributeValue) {
if (attributeValue == null || !attributeValue.isObject()) {
return null;
}
for (String type : List.of("S", "N", "B")) {
JsonNode payload = attributeValue.get(type);
if (payload != null && payload.isTextual()) {
return payload.asText();
}
}
return null;
}
private static String textOrNull(JsonNode node) {
if (node == null || !node.isTextual()) {
return null;
}
String text = node.asText();
return text.isEmpty() ? null : text;
}
}
@@ -0,0 +1,91 @@
package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.AndExpr;
import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.CompareExpr;
import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.Expr;
import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.PathOperand;
import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.PlaceholderOperand;
import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.TokenType;
import java.util.List;
/**
* Narrow read-only view over a Query {@code KeyConditionExpression}: the scalar value the
* partition key is pinned to by an equality condition.
*
* <p>Exists so IAM condition-key extraction can reuse the expression parser without making
* the whole {@link DynamoDbAccessPathValidator} public. Everything here is best effort: a
* malformed or unsupported expression yields {@code null}, and the caller treats that as
* "the leading key could not be determined", which fails closed at the policy layer.
*/
final class DynamoDbKeyConditionParser {
private DynamoDbKeyConditionParser() {}
/**
* @param keyConditionExpression the raw Query KeyConditionExpression
* @param exprAttrNames ExpressionAttributeNames, or {@code null}
* @param exprAttrValues ExpressionAttributeValues, or {@code null}
* @param pkName the table's HASH key attribute name
* @return the S / N / B scalar the partition key equals, or {@code null} when it cannot
* be resolved
*/
static String partitionKeyEqualityValue(String keyConditionExpression,
JsonNode exprAttrNames,
JsonNode exprAttrValues,
String pkName) {
if (keyConditionExpression == null || keyConditionExpression.isBlank()
|| pkName == null || exprAttrValues == null) {
return null;
}
Expr root;
try {
root = ExpressionEvaluator.parse(keyConditionExpression);
} catch (RuntimeException e) {
return null; // unparseable expression → leading key unknown → fail closed upstream
}
if (root == null) {
return null;
}
List<Expr> conditions = root instanceof AndExpr and ? and.operands() : List.of(root);
for (Expr condition : conditions) {
if (!(condition instanceof CompareExpr compare)
|| compare.op() != TokenType.EQ
|| !(compare.right() instanceof PlaceholderOperand placeholder)) {
continue;
}
if (!pkName.equals(topLevelAttribute(compare.left(), exprAttrNames))) {
continue;
}
return scalarValue(exprAttrValues.get(placeholder.name()));
}
return null;
}
/** Resolves a single-segment path operand, following a {@code #alias} when one is used. */
private static String topLevelAttribute(Object operand, JsonNode exprAttrNames) {
if (!(operand instanceof PathOperand path) || path.segments().size() != 1) {
return null;
}
String segment = path.segments().getFirst();
if (segment.startsWith("#") && exprAttrNames != null && exprAttrNames.has(segment)) {
return exprAttrNames.get(segment).asText();
}
return segment;
}
/** Unwraps an AttributeValue to its scalar text. Only S, N and B can be key values. */
private static String scalarValue(JsonNode attributeValue) {
if (attributeValue == null || !attributeValue.isObject()) {
return null;
}
for (String type : List.of("S", "N", "B")) {
JsonNode payload = attributeValue.get(type);
if (payload != null && payload.isTextual()) {
return payload.asText();
}
}
return null;
}
}
@@ -45,6 +45,7 @@ import java.util.LinkedHashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
@@ -396,6 +397,19 @@ public class DynamoDbService implements ResourceProvider {
return table;
}
/**
* The stored table definition without the {@link #describeTable} item-count refresh,
* which is {@code O(items)} on the item map. For callers that only need static metadata
* such as the key schema — notably IAM condition-key resolution, which runs on the
* request hot path before the request is even authorized.
*
* @return the definition, or empty when no such table exists in the region
*/
public Optional<TableDefinition> findTable(String tableName, String region) {
String storageKey = regionKey(region, canonicalTableName(region, tableName));
return tableStore.get(storageKey);
}
public void persistTable(String tableName, TableDefinition table, String region) {
String canonicalTableName = canonicalTableName(region, tableName);
tableStore.put(regionKey(region, canonicalTableName), table);
@@ -72,15 +72,15 @@ public class IamPolicyEvaluator {
* @param resourcePolicies resource-based policy documents (Phase 2); may be null or empty
* @param action IAM action, e.g. "s3:GetObject"
* @param resource resource ARN, e.g. "arn:aws:s3:::my-bucket/key"
* @param conditionCtx condition context key-value pairs; may be null or empty
* @param conditionCtx condition context key → values; may be null or empty
* @return {@link Decision#ALLOW} or {@link Decision#DENY}
*/
public Decision evaluate(CallerContext caller,
List<String> resourcePolicies,
String action,
String resource,
Map<String, String> conditionCtx) {
Map<String, String> ctx = normalizeConditionContext(conditionCtx);
Map<String, List<String>> conditionCtx) {
Map<String, List<String>> ctx = normalizeConditionContext(conditionCtx);
List<PolicyStatement> identityStmts = parseAll(caller.identityPolicies());
List<PolicyStatement> resourceStmts = resourcePolicies == null ? List.of() : parseAll(resourcePolicies);
@@ -139,15 +139,15 @@ public class IamPolicyEvaluator {
public Decision simulateCustomPolicy(List<String> policyDocuments,
String action,
String resource,
Map<String, String> conditionCtx) {
Map<String, List<String>> conditionCtx) {
return evaluate(CallerContext.of(policyDocuments), null, action, resource, conditionCtx);
}
public SimulationDecision simulatePrincipalPolicy(CallerContext caller,
String action,
String resource,
Map<String, String> conditionCtx) {
Map<String, String> ctx = normalizeConditionContext(conditionCtx);
Map<String, List<String>> conditionCtx) {
Map<String, List<String>> ctx = normalizeConditionContext(conditionCtx);
List<PolicyStatement> identityStmts = parseAll(caller.identityPolicies());
List<PolicyStatement> sessionStmts = caller.sessionPolicyDocument() == null
? null : parseAll(List.of(caller.sessionPolicyDocument()));
@@ -183,7 +183,7 @@ public class IamPolicyEvaluator {
* everything the operator meant to forbid.</p>
*/
private boolean scpAllows(List<List<String>> scpLevels, String action, String resource,
Map<String, String> ctx) {
Map<String, List<String>> ctx) {
if (scpLevels == null) {
return true;
}
@@ -208,20 +208,31 @@ public class IamPolicyEvaluator {
// Statement matching
// -----------------------------------------------------------------------
private Map<String, String> normalizeConditionContext(Map<String, String> conditionCtx) {
/**
* Lower-cases keys and copies the value lists, dropping null keys, null lists and null
* members. An empty list is preserved: an empty set is not the same thing as an absent
* key — AWS's set operators give it its own semantics (ForAllValues matches vacuously,
* ForAnyValue does not match).
*/
private Map<String, List<String>> normalizeConditionContext(Map<String, List<String>> conditionCtx) {
if (conditionCtx == null || conditionCtx.isEmpty()) {
return Map.of();
}
return conditionCtx.entrySet().stream()
.filter(entry -> entry.getKey() != null && entry.getValue() != null)
.collect(java.util.stream.Collectors.toMap(
entry -> entry.getKey().toLowerCase(java.util.Locale.ROOT),
Map.Entry::getValue,
(first, ignored) -> first));
Map<String, List<String>> normalized = new LinkedHashMap<>();
for (Map.Entry<String, List<String>> entry : conditionCtx.entrySet()) {
if (entry.getKey() == null || entry.getValue() == null) {
continue;
}
List<String> values = entry.getValue().stream()
.filter(java.util.Objects::nonNull)
.toList();
normalized.putIfAbsent(entry.getKey().toLowerCase(java.util.Locale.ROOT), values);
}
return normalized;
}
private boolean anyExplicitDeny(List<PolicyStatement> stmts, String action, String resource,
Map<String, String> ctx) {
Map<String, List<String>> ctx) {
for (PolicyStatement stmt : stmts) {
if (stmt.isDeny() && matchesStatement(stmt, action, resource, ctx)) {
return true;
@@ -231,7 +242,7 @@ public class IamPolicyEvaluator {
}
private boolean anyExplicitAllow(List<PolicyStatement> stmts, String action, String resource,
Map<String, String> ctx) {
Map<String, List<String>> ctx) {
for (PolicyStatement stmt : stmts) {
if (stmt.isAllow() && matchesStatement(stmt, action, resource, ctx)) {
return true;
@@ -241,7 +252,7 @@ public class IamPolicyEvaluator {
}
private boolean matchesStatement(PolicyStatement stmt, String action, String resource,
Map<String, String> ctx) {
Map<String, List<String>> ctx) {
return matchesAction(stmt, action)
&& matchesResource(stmt, resource)
&& matchesConditions(stmt.getConditions(), ctx);
@@ -290,7 +301,7 @@ public class IamPolicyEvaluator {
* Returns true if ALL blocks pass (or there are no conditions).
*/
private boolean matchesConditions(Map<String, Map<String, List<String>>> conditions,
Map<String, String> ctx) {
Map<String, List<String>> ctx) {
if (conditions == null || conditions.isEmpty()) {
return true;
}
@@ -302,18 +313,82 @@ public class IamPolicyEvaluator {
return true;
}
/**
* AWS set-operator quantifier. {@code ForAllValues:} requires every value the request
* carries for the key to match the policy; {@code ForAnyValue:} requires at least one.
*/
private enum SetQuantifier { NONE, FOR_ALL_VALUES, FOR_ANY_VALUE }
private record ParsedOperator(SetQuantifier quantifier, String baseOp, boolean ifExists) {}
/**
* Splits a condition operator into its set quantifier, base operator and IfExists flag.
* The prefix match is case-sensitive on exactly AWS's own spelling, so a mis-cased
* "forallvalues:" stays an unknown operator instead of silently behaving like the
* real quantifier. The IfExists strip runs on what is left, so
* "ForAnyValue:StringEqualsIfExists" composes correctly.
*/
private static ParsedOperator parseOperator(String operator) {
SetQuantifier quantifier = SetQuantifier.NONE;
String rest = operator;
if (rest.startsWith("ForAllValues:")) {
quantifier = SetQuantifier.FOR_ALL_VALUES;
rest = rest.substring("ForAllValues:".length());
} else if (rest.startsWith("ForAnyValue:")) {
quantifier = SetQuantifier.FOR_ANY_VALUE;
rest = rest.substring("ForAnyValue:".length());
}
boolean ifExists = rest.endsWith("IfExists");
String baseOp = ifExists ? rest.substring(0, rest.length() - "IfExists".length()) : rest;
return new ParsedOperator(quantifier, baseOp, ifExists);
}
/**
* Combines the policy's condition values for a single request value. Positive operators
* OR — the request value may match any listed value. Negated operators AND — the request
* value must differ from every listed value, which is AWS's documented rule for a
* multi-valued negated condition and the deny-list idiom for keys such as
* {@code dynamodb:Attributes} ({@code ForAllValues:StringNotEquals}).
*/
private boolean matchesCondValues(String baseOp, String ctxValue, List<String> condValues) {
if (isNegatedOperator(baseOp)) {
for (String condValue : condValues) {
if (!evaluateSingleCondition(baseOp, ctxValue, condValue)) {
return false;
}
}
return true;
}
for (String condValue : condValues) {
if (evaluateSingleCondition(baseOp, ctxValue, condValue)) {
return true;
}
}
return false;
}
private static boolean isNegatedOperator(String baseOp) {
return switch (baseOp) {
case "StringNotEquals", "StringNotEqualsIgnoreCase", "StringNotLike",
"ArnNotEquals", "ArnNotLike", "NumericNotEquals", "DateNotEquals",
"NotIpAddress" -> true;
default -> false;
};
}
private boolean evaluateConditionBlock(String operator,
Map<String, List<String>> keyValueMap,
Map<String, String> ctx) {
boolean ifExists = operator.endsWith("IfExists");
String baseOp = ifExists ? operator.substring(0, operator.length() - "IfExists".length()) : operator;
Map<String, List<String>> ctx) {
ParsedOperator parsed = parseOperator(operator);
String baseOp = parsed.baseOp();
boolean ifExists = parsed.ifExists();
for (Map.Entry<String, List<String>> entry : keyValueMap.entrySet()) {
String condKey = entry.getKey().toLowerCase();
String condKey = entry.getKey().toLowerCase(java.util.Locale.ROOT);
List<String> condValues = entry.getValue();
String ctxValue = ctx.get(condKey);
List<String> ctxValues = ctx.get(condKey);
if (ctxValue == null) {
if (ctxValues == null) {
if ("Null".equalsIgnoreCase(baseOp)) {
// Null: {key: "true"} → key must be absent → pass when any condValue is "true"
boolean expectAbsent = condValues.stream().anyMatch("true"::equalsIgnoreCase);
@@ -329,22 +404,31 @@ public class IamPolicyEvaluator {
}
if ("Null".equalsIgnoreCase(baseOp)) {
// Key is present — Null:{key:"true"} should fail, Null:{key:"false"} should pass
// Key is present. An empty set counts as nonexistent for Null, matching AWS,
// so the Null:{key:"false"} guard that policies pair with ForAllValues still
// blocks a vacuous match. Null:{key:"true"} passes only when effectively absent.
boolean expectAbsent = condValues.stream().anyMatch("true"::equalsIgnoreCase);
if (expectAbsent) {
return false; // expected absent but key has value
boolean effectivelyAbsent = ctxValues.isEmpty();
if (expectAbsent != effectivelyAbsent) {
return false;
}
continue;
}
// OR across condValues for this key
boolean keyMatch = false;
for (String condValue : condValues) {
if (evaluateSingleCondition(baseOp, ctxValue, condValue)) {
keyMatch = true;
break;
}
}
boolean keyMatch = switch (parsed.quantifier()) {
// Every request value must match at least one policy value. An empty set
// matches vacuously, which is why real policies pair ForAllValues with a
// Null:{key:"false"} guard.
case FOR_ALL_VALUES -> ctxValues.stream()
.allMatch(ctxValue -> matchesCondValues(baseOp, ctxValue, condValues));
// At least one request value must match. An empty set never matches.
case FOR_ANY_VALUE -> ctxValues.stream()
.anyMatch(ctxValue -> matchesCondValues(baseOp, ctxValue, condValues));
// A bare operator against a multi-valued key is a policy authoring error in
// AWS; mirror that by comparing only the first value.
case NONE -> !ctxValues.isEmpty()
&& matchesCondValues(baseOp, ctxValues.getFirst(), condValues);
};
if (!keyMatch) {
return false;
}
@@ -352,6 +436,7 @@ public class IamPolicyEvaluator {
return true;
}
private boolean evaluateSingleCondition(String operator, String ctxValue, String condValue) {
return switch (operator) {
case "StringEquals" -> ctxValue.equals(condValue);
@@ -1174,7 +1174,7 @@ public class IamQueryHandler {
if (resourceArns.isEmpty()) {
resourceArns = List.of("*");
}
Map<String, String> context = extractContextEntries(params);
Map<String, List<String>> context = extractContextEntries(params);
XmlBuilder results = new XmlBuilder().start("EvaluationResults");
for (String actionName : actionNames) {
@@ -1402,14 +1402,21 @@ public class IamQueryHandler {
return values;
}
private Map<String, String> extractContextEntries(MultivaluedMap<String, String> params) {
Map<String, String> context = new HashMap<>();
/**
* Reads every {@code ContextEntries.member.N.ContextKeyValues.member.M}. AWS context keys
* are set-typed, and the evaluator's set operators quantify over the whole set, so reading
* only {@code member.1} silently dropped the values a ForAnyValue:/ForAllValues: condition
* has to see. An entry that names a key but supplies no value is skipped.
*/
private Map<String, List<String>> extractContextEntries(MultivaluedMap<String, String> params) {
Map<String, List<String>> context = new HashMap<>();
for (int i = 1; ; i++) {
String name = params.getFirst("ContextEntries.member." + i + ".ContextKeyName");
if (name == null) break;
String value = params.getFirst("ContextEntries.member." + i + ".ContextKeyValues.member.1");
if (value != null) {
context.put(name, value);
List<String> values = extractIndexedValues(
params, "ContextEntries.member." + i + ".ContextKeyValues.member");
if (!values.isEmpty()) {
context.put(name, values);
}
}
return context;
@@ -1,21 +1,69 @@
package io.github.hectorvent.floci.core.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import jakarta.enterprise.inject.Instance;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class IamConditionContextResolverTest {
private final IamConditionContextResolver resolver = new IamConditionContextResolver();
private final ObjectMapper mapper = new ObjectMapper();
private DynamoDbService dynamoDbService;
private Instance<DynamoDbService> dynamoDbServiceInstance;
private RequestContext requestContext;
private EmulatorConfig config;
private IamConditionContextResolver resolver;
@SuppressWarnings("unchecked")
@BeforeEach
void setUp() {
dynamoDbService = mock(DynamoDbService.class);
dynamoDbServiceInstance = mock(Instance.class);
when(dynamoDbServiceInstance.isResolvable()).thenReturn(true);
when(dynamoDbServiceInstance.get()).thenReturn(dynamoDbService);
requestContext = new RequestContext();
requestContext.setRegion("us-east-1");
config = mock(EmulatorConfig.class);
when(config.defaultRegion()).thenReturn("us-east-1");
resolver = new IamConditionContextResolver(
dynamoDbServiceInstance, requestContext, config);
}
private TableDefinition fgacTable() {
TableDefinition table = new TableDefinition();
table.setTableName("FgacTable");
table.setKeySchema(List.of(new KeySchemaElement("PK", "HASH")));
return table;
}
private JsonNode json(String raw) {
try {
return mapper.readTree(raw);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
@Test
void resolvesS3ListBucketQueryConditionContext() {
@@ -29,11 +77,12 @@ class IamConditionContextResolverTest {
when(containerRequest.getUriInfo()).thenReturn(uriInfo);
when(uriInfo.getQueryParameters()).thenReturn(query);
Map<String, String> conditions = resolver.resolve("s3", "s3:ListBucket", containerRequest);
Map<String, List<String>> conditions =
resolver.resolve("s3", "s3:ListBucket", containerRequest);
assertEquals("my_namespace/table/", conditions.get("s3:prefix"));
assertEquals("/", conditions.get("s3:delimiter"));
assertEquals("100", conditions.get("s3:max-keys"));
assertEquals(List.of("my_namespace/table/"), conditions.get("s3:prefix"));
assertEquals(List.of("/"), conditions.get("s3:delimiter"));
assertEquals(List.of("100"), conditions.get("s3:max-keys"));
}
@Test
@@ -48,4 +97,90 @@ class IamConditionContextResolverTest {
assertNull(resolver.resolve("lambda", "lambda:InvokeFunction", containerRequest));
assertNull(resolver.resolve("s3", "s3:GetObject", containerRequest));
}
@Test
void resolvesDynamoDbLeadingKeysForGetItem() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
when(containerRequest.getProperty("floci.bufferedJsonBody")).thenReturn(json("""
{"TableName":"FgacTable","Key":{"PK":{"S":"USER_alice"}}}"""));
when(dynamoDbService.findTable("FgacTable", "us-east-1")).thenReturn(Optional.of(fgacTable()));
Map<String, List<String>> conditions =
resolver.resolve("dynamodb", "dynamodb:GetItem", containerRequest);
assertEquals(List.of("USER_alice"), conditions.get("dynamodb:LeadingKeys"));
assertEquals(List.of("PK"), conditions.get("dynamodb:Attributes"));
assertFalse(conditions.containsKey("dynamodb:Select"));
}
@Test
void omitsLeadingKeysWhenTheTableIsUnknown() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
when(containerRequest.getProperty("floci.bufferedJsonBody")).thenReturn(json("""
{"TableName":"MissingTable","Key":{"PK":{"S":"USER_alice"}}}"""));
when(dynamoDbService.findTable(eq("MissingTable"), anyString()))
.thenReturn(Optional.empty());
Map<String, List<String>> conditions =
resolver.resolve("dynamodb", "dynamodb:GetItem", containerRequest);
assertFalse(conditions.containsKey("dynamodb:LeadingKeys"));
// Attribute names do not depend on the key schema, so they are still populated.
assertEquals(List.of("PK"), conditions.get("dynamodb:Attributes"));
}
@Test
void carriesSelectForQuery() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
when(containerRequest.getProperty("floci.bufferedJsonBody")).thenReturn(json("""
{"TableName":"FgacTable",
"KeyConditionExpression":"PK = :v",
"ExpressionAttributeValues":{":v":{"S":"USER_alice"}},
"Select":"COUNT"}"""));
when(dynamoDbService.findTable("FgacTable", "us-east-1")).thenReturn(Optional.of(fgacTable()));
Map<String, List<String>> conditions =
resolver.resolve("dynamodb", "dynamodb:Query", containerRequest);
assertEquals(List.of("USER_alice"), conditions.get("dynamodb:LeadingKeys"));
assertEquals(List.of("COUNT"), conditions.get("dynamodb:Select"));
}
@Test
void returnsNullWhenNoBodyWasBuffered() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
when(containerRequest.getProperty("floci.bufferedJsonBody")).thenReturn(null);
assertNull(resolver.resolve("dynamodb", "dynamodb:GetItem", containerRequest));
}
@Test
void resolvesBatchGetItemAcrossEveryRequestedKey() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
when(containerRequest.getProperty("floci.bufferedJsonBody")).thenReturn(json("""
{"RequestItems":{"FgacTable":{"Keys":[
{"PK":{"S":"USER_alice"}},{"PK":{"S":"USER_bob"}}]}}}"""));
when(dynamoDbService.findTable("FgacTable", "us-east-1")).thenReturn(Optional.of(fgacTable()));
Map<String, List<String>> conditions =
resolver.resolve("dynamodb", "dynamodb:BatchGetItem", containerRequest);
assertEquals(List.of("USER_alice", "USER_bob"), conditions.get("dynamodb:LeadingKeys"));
}
@Test
void omitsLeadingKeysForAMultiTableBatch() {
// A batch spanning two tables has no single key schema: applying table A's partition
// key name to table B's items would be wrong, so no leading keys are produced.
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
when(containerRequest.getProperty("floci.bufferedJsonBody")).thenReturn(json("""
{"RequestItems":{
"FgacTable":{"Keys":[{"PK":{"S":"USER_alice"}}]},
"OtherTable":{"Keys":[{"PK":{"S":"USER_bob"}}]}}}"""));
Map<String, List<String>> conditions =
resolver.resolve("dynamodb", "dynamodb:BatchGetItem", containerRequest);
assertFalse(conditions.containsKey("dynamodb:LeadingKeys"));
}
}
@@ -256,7 +256,7 @@ class IamEnforcementFilterTest {
@Test
void filterPassesS3ListBucketConditionContext() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
Map<String, String> conditions = Map.of("s3:prefix", "my_namespace/table/");
Map<String, List<String>> conditions = Map.of("s3:prefix", List.of("my_namespace/table/"));
String auth = "AWS4-HMAC-SHA256 Credential=ASIASESSION/20260706/us-east-1/s3/aws4_request, "
+ "SignedHeaders=host, Signature=abc";
@@ -0,0 +1,360 @@
package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex;
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
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 java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class DynamoDbConditionKeysTest {
private final ObjectMapper mapper = new ObjectMapper();
private TableDefinition table;
@BeforeEach
void setUp() {
table = new TableDefinition();
table.setTableName("FgacTable");
table.setKeySchema(List.of(
new KeySchemaElement("PK", "HASH"),
new KeySchemaElement("SK", "RANGE")));
}
private JsonNode json(String raw) {
try {
return mapper.readTree(raw);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
@Test
void getItemExposesTheKeyValueAndTheKeyAttributeNames() {
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:GetItem",
json("""
{"TableName":"FgacTable",
"Key":{"PK":{"S":"USER_alice"},"SK":{"S":"profile"}}}"""),
table);
assertEquals(List.of("USER_alice"), result.leadingKeys());
assertEquals(List.of("PK", "SK"), result.attributes());
assertNull(result.select());
}
@Test
void putItemExposesTheItemPartitionKeyAndEveryItemAttribute() {
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:PutItem",
json("""
{"TableName":"FgacTable",
"Item":{"PK":{"S":"USER_alice"},"SK":{"S":"profile"},"email":{"S":"a@b.c"}}}"""),
table);
assertEquals(List.of("USER_alice"), result.leadingKeys());
assertEquals(List.of("PK", "SK", "email"), result.attributes());
}
@Test
void updateItemExposesTheKeyValueAndTheUpdateExpressionTargets() {
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:UpdateItem",
json("""
{"TableName":"FgacTable",
"Key":{"PK":{"S":"USER_alice"},"SK":{"S":"profile"}},
"UpdateExpression":"SET #e = :e REMOVE nickname",
"ExpressionAttributeNames":{"#e":"email"},
"ExpressionAttributeValues":{":e":{"S":"a@b.c"}}}"""),
table);
assertEquals(List.of("USER_alice"), result.leadingKeys());
assertTrue(result.attributes().contains("PK"), result.attributes().toString());
assertTrue(result.attributes().contains("email"), result.attributes().toString());
assertTrue(result.attributes().contains("nickname"), result.attributes().toString());
}
@Test
void deleteItemExposesTheKeyValue() {
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:DeleteItem",
json("""
{"TableName":"FgacTable","Key":{"PK":{"S":"USER_bob"},"SK":{"S":"profile"}}}"""),
table);
assertEquals(List.of("USER_bob"), result.leadingKeys());
}
@Test
void queryResolvesTheLeadingKeyFromTheKeyConditionExpressionAndCarriesSelect() {
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:Query",
json("""
{"TableName":"FgacTable",
"KeyConditionExpression":"PK = :v AND SK > :s",
"ExpressionAttributeValues":{":v":{"S":"USER_alice"},":s":{"S":"2020"}},
"ProjectionExpression":"email, #n",
"ExpressionAttributeNames":{"#n":"nickname"},
"Select":"SPECIFIC_ATTRIBUTES"}"""),
table);
assertEquals(List.of("USER_alice"), result.leadingKeys());
assertEquals("SPECIFIC_ATTRIBUTES", result.select());
assertTrue(result.attributes().contains("email"), result.attributes().toString());
assertTrue(result.attributes().contains("nickname"), result.attributes().toString());
}
@Test
void queryResolvesAnAliasedPartitionKey() {
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:Query",
json("""
{"TableName":"FgacTable",
"KeyConditionExpression":"#p = :v",
"ExpressionAttributeNames":{"#p":"PK"},
"ExpressionAttributeValues":{":v":{"S":"USER_alice"}}}"""),
table);
assertEquals(List.of("USER_alice"), result.leadingKeys());
}
@Test
void batchGetItemExposesEveryRequestedKey() {
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:BatchGetItem",
json("""
{"RequestItems":{"FgacTable":{"Keys":[
{"PK":{"S":"USER_alice"},"SK":{"S":"a"}},
{"PK":{"S":"USER_alice_2"},"SK":{"S":"b"}},
{"PK":{"S":"USER_bob"},"SK":{"S":"c"}}]}}}"""),
table);
assertEquals(List.of("USER_alice", "USER_alice_2", "USER_bob"), result.leadingKeys());
}
@Test
void batchWriteItemExposesPutAndDeleteKeys() {
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:BatchWriteItem",
json("""
{"RequestItems":{"FgacTable":[
{"PutRequest":{"Item":{"PK":{"S":"USER_alice"},"SK":{"S":"a"}}}},
{"DeleteRequest":{"Key":{"PK":{"S":"USER_bob"},"SK":{"S":"b"}}}}]}}"""),
table);
assertEquals(List.of("USER_alice", "USER_bob"), result.leadingKeys());
}
@Test
void nullTableYieldsNoLeadingKeysAndDoesNotThrow() {
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:GetItem",
json("""
{"TableName":"FgacTable","Key":{"PK":{"S":"USER_alice"}}}"""),
null);
assertTrue(result.leadingKeys().isEmpty());
assertEquals(List.of("PK"), result.attributes());
}
@Test
void aKeyMissingThePartitionAttributeYieldsNoLeadingKeys() {
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:GetItem",
json("""
{"TableName":"FgacTable","Key":{"SK":{"S":"profile"}}}"""),
table);
assertTrue(result.leadingKeys().isEmpty());
}
@Test
void nullBodyYieldsAnEmptyResult() {
DynamoDbConditionKeys.Result result =
DynamoDbConditionKeys.extract("dynamodb:GetItem", null, table);
assertTrue(result.leadingKeys().isEmpty());
assertTrue(result.attributes().isEmpty());
assertNull(result.select());
}
@Test
void queryCollectsLiteralAttributeNamesFromAFilterExpression() {
// A projection of only allowed attributes must not hide a filter on a forbidden one.
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:Query",
json("""
{"TableName":"FgacTable",
"KeyConditionExpression":"PK = :v",
"ExpressionAttributeValues":{":v":{"S":"USER_alice"},":x":{"S":"y"}},
"FilterExpression":"ssn = :x",
"ProjectionExpression":"email"}"""),
table);
assertTrue(result.attributes().contains("ssn"), result.attributes().toString());
assertTrue(result.attributes().contains("email"), result.attributes().toString());
assertTrue(result.attributes().contains("PK"), result.attributes().toString());
}
@Test
void putItemCollectsLiteralAttributeNamesFromAConditionExpression() {
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:PutItem",
json("""
{"TableName":"FgacTable",
"Item":{"PK":{"S":"USER_alice"},"SK":{"S":"profile"}},
"ConditionExpression":"attribute_not_exists(locked)"}"""),
table);
assertTrue(result.attributes().contains("locked"), result.attributes().toString());
}
@Test
void queryResolvesTheLeadingKeyFromALegacyKeyConditionsMap() {
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:Query",
json("""
{"TableName":"FgacTable",
"KeyConditions":{"PK":{"ComparisonOperator":"EQ",
"AttributeValueList":[{"S":"USER_alice"}]}}}"""),
table);
assertEquals(List.of("USER_alice"), result.leadingKeys());
assertTrue(result.attributes().contains("PK"), result.attributes().toString());
}
@Test
void attributesToGetAreExposed() {
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:GetItem",
json("""
{"TableName":"FgacTable","Key":{"PK":{"S":"USER_alice"}},
"AttributesToGet":["email","nickname"]}"""),
table);
assertTrue(result.attributes().contains("email"), result.attributes().toString());
assertTrue(result.attributes().contains("nickname"), result.attributes().toString());
}
@Test
void queryAgainstGsiResolvesGsiPartitionKeyAsLeadingKey() {
GlobalSecondaryIndex gsi = new GlobalSecondaryIndex();
gsi.setIndexName("EmailGSI");
gsi.setKeySchema(List.of(
new KeySchemaElement("GSI_PK", "HASH"),
new KeySchemaElement("GSI_SK", "RANGE")));
table.setGlobalSecondaryIndexes(List.of(gsi));
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:Query",
json("""
{"TableName":"FgacTable",
"IndexName":"EmailGSI",
"KeyConditionExpression":"GSI_PK = :email",
"ExpressionAttributeValues":{":email":{"S":"alice@example.com"}}}"""),
table);
assertEquals(List.of("alice@example.com"), result.leadingKeys());
assertTrue(result.attributes().contains("GSI_PK"), result.attributes().toString());
}
@Test
void queryAgainstLsiResolvesTablePartitionKeyAsLeadingKey() {
LocalSecondaryIndex lsi = new LocalSecondaryIndex();
lsi.setIndexName("CreatedLSI");
lsi.setKeySchema(List.of(
new KeySchemaElement("PK", "HASH"),
new KeySchemaElement("CreatedAt", "RANGE")));
table.setLocalSecondaryIndexes(List.of(lsi));
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:Query",
json("""
{"TableName":"FgacTable",
"IndexName":"CreatedLSI",
"KeyConditionExpression":"PK = :pk",
"ExpressionAttributeValues":{":pk":{"S":"USER_alice"}}}"""),
table);
assertEquals(List.of("USER_alice"), result.leadingKeys());
assertTrue(result.attributes().contains("PK"), result.attributes().toString());
}
@Test
void updateItemExposesReadOperandsAndTargetsFromUpdateExpression() {
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:UpdateItem",
json("""
{"TableName":"FgacTable",
"Key":{"PK":{"S":"USER_alice"},"SK":{"S":"profile"}},
"UpdateExpression":"SET total = price + :tax, history = list_append(oldHistory, :entry), city = if_not_exists(fallbackCity, :def) REMOVE oldFlag, tags[0] ADD score :pts DELETE categories :cat",
"ExpressionAttributeValues":{":tax":{"N":"5"},":entry":{"S":"login"},":def":{"S":"HN"},":pts":{"N":"1"},":cat":{"SS":["old"]}}}"""),
table);
assertEquals(List.of("USER_alice"), result.leadingKeys());
assertTrue(result.attributes().contains("total"), result.attributes().toString());
assertTrue(result.attributes().contains("price"), result.attributes().toString());
assertTrue(result.attributes().contains("history"), result.attributes().toString());
assertTrue(result.attributes().contains("oldHistory"), result.attributes().toString());
assertTrue(result.attributes().contains("city"), result.attributes().toString());
assertTrue(result.attributes().contains("fallbackCity"), result.attributes().toString());
assertTrue(result.attributes().contains("oldFlag"), result.attributes().toString());
assertTrue(result.attributes().contains("tags"), result.attributes().toString());
assertTrue(result.attributes().contains("score"), result.attributes().toString());
assertTrue(result.attributes().contains("categories"), result.attributes().toString());
}
@Test
void updateItemDoesNotExposeNestedAttributeNamesAsTopLevelAttributes() {
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:UpdateItem",
json("""
{"TableName":"FgacTable",
"Key":{"PK":{"S":"USER_alice"}},
"UpdateExpression":"SET #a.subfield = :v, nested[0].detail = :d",
"ExpressionAttributeNames":{"#a":"actualTop"},
"ExpressionAttributeValues":{":v":{"S":"val"},":d":{"S":"detail"}}}"""),
table);
assertTrue(result.attributes().contains("actualTop"), result.attributes().toString());
assertTrue(result.attributes().contains("nested"), result.attributes().toString());
assertFalse(result.attributes().contains("subfield"), result.attributes().toString());
assertFalse(result.attributes().contains("detail"), result.attributes().toString());
}
@Test
void legacyAttributeUpdatesAndExpectedAreExposedAsAttributes() {
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:UpdateItem",
json("""
{"TableName":"FgacTable",
"Key":{"PK":{"S":"USER_alice"}},
"AttributeUpdates":{"status":{"Action":"PUT","Value":{"S":"active"}}},
"Expected":{"version":{"ComparisonOperator":"EQ","AttributeValueList":[{"N":"1"}]}}}"""),
table);
assertTrue(result.attributes().contains("status"), result.attributes().toString());
assertTrue(result.attributes().contains("version"), result.attributes().toString());
}
@Test
void scanExposesLegacyScanFilterAttributes() {
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
"dynamodb:Scan",
json("""
{"TableName":"FgacTable",
"ScanFilter":{"inStock":{"ComparisonOperator":"EQ","AttributeValueList":[{"BOOL":true}]}}}"""),
table);
assertTrue(result.attributes().contains("inStock"), result.attributes().toString());
}
}
@@ -0,0 +1,85 @@
package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
class DynamoDbKeyConditionParserTest {
private final ObjectMapper mapper = new ObjectMapper();
private JsonNode json(String raw) {
try {
return mapper.readTree(raw);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
@Test
void resolvesSimplePartitionKeyEquality() {
assertEquals("USER_alice", DynamoDbKeyConditionParser.partitionKeyEqualityValue(
"pk = :v", null, json("{\":v\":{\"S\":\"USER_alice\"}}"), "pk"));
}
@Test
void resolvesPartitionKeyEqualityAlongsideASortKeyCondition() {
assertEquals("USER_alice", DynamoDbKeyConditionParser.partitionKeyEqualityValue(
"pk = :v AND sk > :s", null,
json("{\":v\":{\"S\":\"USER_alice\"},\":s\":{\"S\":\"2020\"}}"), "pk"));
}
@Test
void resolvesAnAliasedPartitionKeyThroughExpressionAttributeNames() {
assertEquals("USER_alice", DynamoDbKeyConditionParser.partitionKeyEqualityValue(
"#p = :v", json("{\"#p\":\"pk\"}"),
json("{\":v\":{\"S\":\"USER_alice\"}}"), "pk"));
}
@Test
void resolvesNumericAndBinaryPartitionKeys() {
assertEquals("42", DynamoDbKeyConditionParser.partitionKeyEqualityValue(
"pk = :v", null, json("{\":v\":{\"N\":\"42\"}}"), "pk"));
assertEquals("YWJj", DynamoDbKeyConditionParser.partitionKeyEqualityValue(
"pk = :v", null, json("{\":v\":{\"B\":\"YWJj\"}}"), "pk"));
}
@Test
void returnsNullWhenThePartitionKeyIsNotPinnedByEquality() {
assertNull(DynamoDbKeyConditionParser.partitionKeyEqualityValue(
"sk > :s", null, json("{\":s\":{\"S\":\"2020\"}}"), "pk"));
}
@Test
void returnsNullForABeginsWithConditionOnThePartitionKey() {
// begins_with is a valid sort-key condition but never an equality; treating it as
// one would pin the leading key to a prefix and wrongly allow a whole partition range.
assertNull(DynamoDbKeyConditionParser.partitionKeyEqualityValue(
"begins_with(pk, :v)", null, json("{\":v\":{\"S\":\"USER_\"}}"), "pk"));
}
@Test
void returnsNullWhenThePartitionKeyEqualityIsUnderAnOr() {
// A top-level OR means the request is not constrained to a single partition value.
assertNull(DynamoDbKeyConditionParser.partitionKeyEqualityValue(
"pk = :a OR pk = :b", null,
json("{\":a\":{\"S\":\"USER_alice\"},\":b\":{\"S\":\"USER_bob\"}}"), "pk"));
}
@Test
void returnsNullOnUnparseableOrMissingInput() {
assertNull(DynamoDbKeyConditionParser.partitionKeyEqualityValue(
"pk = = :v", null, json("{\":v\":{\"S\":\"x\"}}"), "pk"));
assertNull(DynamoDbKeyConditionParser.partitionKeyEqualityValue(
null, null, json("{}"), "pk"));
assertNull(DynamoDbKeyConditionParser.partitionKeyEqualityValue(
"pk = :v", null, null, "pk"));
assertNull(DynamoDbKeyConditionParser.partitionKeyEqualityValue(
"pk = :v", null, json("{\":other\":{\"S\":\"x\"}}"), "pk"));
assertNull(DynamoDbKeyConditionParser.partitionKeyEqualityValue(
"pk = :v", null, json("{\":v\":{\"S\":\"x\"}}"), null));
}
}
@@ -0,0 +1,307 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
/**
* End-to-end proof of the scenario in issue #2926: one session scoped by
* ForAllValues:StringLike on dynamodb:LeadingKeys reads its own partition and is denied
* another tenant's, through the real filter, resolver and evaluator.
*/
@QuarkusTest
@TestProfile(DynamoDbFgacEnforcementIntegrationTest.IamEnforcementProfile.class)
class DynamoDbFgacEnforcementIntegrationTest {
private static final String DYNAMODB_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String CALLER_ACCOUNT_ID = "111122223333";
private static final String ROLE_ACCOUNT_ID = "222233334444";
private static final String REGION = "us-east-1";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void leadingKeysScopedSessionReadsItsOwnPartitionAndIsDeniedAnotherTenants() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String tableName = "fgac-" + suffix;
String roleName = "FgacRole" + suffix;
createTable(tableName);
putItem(tableName, "USER_alice");
putItem(tableName, "USER_bob");
createRole(roleName);
putBroadDynamoDbRolePolicy(roleName);
String accessKeyId = assumeRoleWithLeadingKeysSessionPolicy(roleName);
// In scope: the session policy's ForAllValues:StringLike matches USER_alice*.
given()
.header("Authorization", auth(accessKeyId, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20120810.GetItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"TableName":"%s","Key":{"PK":{"S":"USER_alice"}}}"""
.formatted(tableName))
.when()
.post("/")
.then()
.statusCode(200)
.body("Item.PK.S", equalTo("USER_alice"));
// Out of scope: same session, same table, different partition.
given()
.header("Authorization", auth(accessKeyId, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20120810.GetItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"TableName":"%s","Key":{"PK":{"S":"USER_bob"}}}"""
.formatted(tableName))
.when()
.post("/")
.then()
.statusCode(403)
.body(containsString("AccessDeniedException"));
}
@Test
void requestThatCannotProveItsLeadingKeyIsDenied() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String tableName = "fgac-noprove-" + suffix;
String roleName = "FgacNoProveRole" + suffix;
createTable(tableName);
createRole(roleName);
putBroadDynamoDbRolePolicy(roleName);
String accessKeyId = assumeRoleWithLeadingKeysSessionPolicy(roleName);
// The Key omits the partition attribute, so the leading key cannot be resolved. With
// access scoped purely through dynamodb:LeadingKeys this is denied rather than passed
// to DynamoDB, which is the correct direction for a security boundary.
given()
.header("Authorization", auth(accessKeyId, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20120810.GetItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"TableName":"%s","Key":{"SK":{"S":"profile"}}}"""
.formatted(tableName))
.when()
.post("/")
.then()
.statusCode(403)
.body(containsString("AccessDeniedException"));
}
@Test
void leadingKeysScopedSessionQueriesGsiByItsOwnPartitionKeyAndIsDeniedAnother() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String tableName = "fgac-gsi-" + suffix;
String roleName = "FgacGsiRole" + suffix;
createTableWithGsi(tableName, "TenantGSI");
putItemWithGsiKey(tableName, "item-1", "USER_alice");
putItemWithGsiKey(tableName, "item-2", "USER_bob");
createRole(roleName);
putBroadDynamoDbRolePolicy(roleName);
String accessKeyId = assumeRoleWithLeadingKeysSessionPolicy(roleName);
// In scope: query targets GSI partition key matching USER_alice*.
given()
.header("Authorization", auth(accessKeyId, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20120810.Query")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"TableName":"%s",
"IndexName":"TenantGSI",
"KeyConditionExpression":"GSI_PK = :gsi",
"ExpressionAttributeValues":{":gsi":{"S":"USER_alice"}}}"""
.formatted(tableName))
.when()
.post("/")
.then()
.statusCode(200)
.body("Count", equalTo(1))
.body("Items[0].PK.S", equalTo("item-1"));
// Out of scope: query targets GSI partition key of another tenant.
given()
.header("Authorization", auth(accessKeyId, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20120810.Query")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"TableName":"%s",
"IndexName":"TenantGSI",
"KeyConditionExpression":"GSI_PK = :gsi",
"ExpressionAttributeValues":{":gsi":{"S":"USER_bob"}}}"""
.formatted(tableName))
.when()
.post("/")
.then()
.statusCode(403)
.body(containsString("AccessDeniedException"));
}
private static void createTable(String tableName) {
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"}],
"AttributeDefinitions":[{"AttributeName":"PK","AttributeType":"S"}],
"BillingMode":"PAY_PER_REQUEST"}"""
.formatted(tableName))
.when()
.post("/")
.then()
.statusCode(200);
}
private static void putItem(String tableName, String partitionKey) {
given()
.header("Authorization", auth(ROLE_ACCOUNT_ID, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20120810.PutItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"TableName":"%s","Item":{"PK":{"S":"%s"},"email":{"S":"x@y.z"}}}"""
.formatted(tableName, partitionKey))
.when()
.post("/")
.then()
.statusCode(200);
}
private static void createTableWithGsi(String tableName, String indexName) {
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"}],
"AttributeDefinitions":[
{"AttributeName":"PK","AttributeType":"S"},
{"AttributeName":"GSI_PK","AttributeType":"S"}
],
"GlobalSecondaryIndexes":[
{
"IndexName":"%s",
"KeySchema":[{"AttributeName":"GSI_PK","KeyType":"HASH"}],
"Projection":{"ProjectionType":"ALL"}
}
],
"BillingMode":"PAY_PER_REQUEST"}"""
.formatted(tableName, indexName))
.when()
.post("/")
.then()
.statusCode(200);
}
private static void putItemWithGsiKey(String tableName, String partitionKey, String gsiKey) {
given()
.header("Authorization", auth(ROLE_ACCOUNT_ID, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20120810.PutItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"TableName":"%s","Item":{"PK":{"S":"%s"},"GSI_PK":{"S":"%s"},"email":{"S":"x@y.z"}}}"""
.formatted(tableName, partitionKey, gsiKey))
.when()
.post("/")
.then()
.statusCode(200);
}
private static void createRole(String roleName) {
given()
.formParam("Action", "CreateRole")
.formParam("RoleName", roleName)
.formParam("Path", "/")
.formParam("AssumeRolePolicyDocument", """
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "AWS": "*" },
"Action": "sts:AssumeRole"
}
]
}
""")
.header("Authorization", auth(ROLE_ACCOUNT_ID, "iam"))
.when()
.post("/")
.then()
.statusCode(200);
}
private static void putBroadDynamoDbRolePolicy(String roleName) {
given()
.formParam("Action", "PutRolePolicy")
.formParam("RoleName", roleName)
.formParam("PolicyName", "AllowDynamoDb")
.formParam("PolicyDocument", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:*","Resource":"*"}
]}""")
.header("Authorization", auth(ROLE_ACCOUNT_ID, "iam"))
.when()
.post("/")
.then()
.statusCode(200);
}
/**
* The session policy is the only thing that discriminates: Resource is "*", so an
* allow or a deny can only come from the LeadingKeys condition.
*/
private static String assumeRoleWithLeadingKeysSessionPolicy(String roleName) {
return given()
.formParam("Action", "AssumeRole")
.formParam("RoleArn", "arn:aws:iam::" + ROLE_ACCOUNT_ID + ":role/" + roleName)
.formParam("RoleSessionName", "fgac-leading-keys-test")
.formParam("Policy", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:*","Resource":"*",
"Condition":{"ForAllValues:StringLike":
{"dynamodb:LeadingKeys":["USER_alice*"]}}}
]}""")
.header("Authorization", auth(CALLER_ACCOUNT_ID, "sts"))
.when()
.post("/")
.then()
.statusCode(200)
.body("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId", startsWith("ASIA"))
.extract()
.path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId");
}
private static String auth(String accessKeyId, String service) {
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260904/" + REGION + "/" + service
+ "/aws4_request, SignedHeaders=host, Signature=abc";
}
public static final class IamEnforcementProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.iam.enforcement-enabled", "true");
}
}
}
@@ -148,7 +148,7 @@ class IamEnforcementIntegrationTest {
List.of(policy),
"s3:GetObject",
"arn:aws:s3:::bucket/key",
Map.of("AWS:SourceIP", "127.0.0.1")));
Map.of("AWS:SourceIP", List.of("127.0.0.1"))));
}
// =========================================================================
@@ -188,4 +188,48 @@ class IamEnforcementIntegrationTest {
"arn:aws:s3:::my-bucket/*",
"arn:aws:s3:::other-bucket/file.txt"));
}
// =========================================================================
// DynamoDB fine-grained access control (issue #2926)
// =========================================================================
private static final String LEADING_KEYS_SCOPED_POLICY = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["dynamodb:GetItem","dynamodb:Query"],
"Resource":"arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable",
"Condition":{"ForAllValues:StringLike":{"dynamodb:LeadingKeys":["USER_alice*"]}}}
]}""";
@Test
void leadingKeysConditionAllowsTheInScopeItemAndDeniesTheOutOfScopeOne() {
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(
List.of(LEADING_KEYS_SCOPED_POLICY), "dynamodb:GetItem",
"arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable",
Map.of("dynamodb:LeadingKeys", List.of("USER_alice"))));
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
List.of(LEADING_KEYS_SCOPED_POLICY), "dynamodb:GetItem",
"arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable",
Map.of("dynamodb:LeadingKeys", List.of("USER_bob"))));
// The leading key could not be resolved from the request: fail closed.
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
List.of(LEADING_KEYS_SCOPED_POLICY), "dynamodb:GetItem",
"arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable",
Map.of()));
}
@Test
void wildcardActionAndResourcePolicyStillAllowsRegardlessOfLeadingKeys() {
// Control: the condition is what discriminates above, not the action or the ARN.
String wildcard = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"*","Resource":"*"}
]}""";
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(
List.of(wildcard), "dynamodb:GetItem",
"arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable",
Map.of("dynamodb:LeadingKeys", List.of("USER_bob"))));
}
}
@@ -1117,4 +1117,54 @@ class IamIntegrationTest {
.body(containsString("ListPoliciesOmitCheckPolicy"))
.body(not(containsString("<Description>")));
}
@Test
void simulatePrincipalPolicyReadsEveryContextKeyValue() {
// A ForAnyValue: condition is satisfied only by the SECOND supplied context value,
// so a handler that reads only ContextKeyValues.member.1 returns implicitDeny.
given()
.formParam("Action", "CreateUser")
.formParam("UserName", "multi-context-user")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260904/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "PutUserPolicy")
.formParam("UserName", "multi-context-user")
.formParam("PolicyName", "AllowAliceLeadingKeys")
.formParam("PolicyDocument", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
"Condition":{"ForAnyValue:StringEquals":{"dynamodb:LeadingKeys":["USER_alice"]}}}
]}""")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260904/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "SimulatePrincipalPolicy")
.formParam("PolicySourceArn", "arn:aws:iam::000000000000:user/multi-context-user")
.formParam("ActionNames.member.1", "dynamodb:GetItem")
.formParam("ResourceArns.member.1", "*")
.formParam("ContextEntries.member.1.ContextKeyName", "dynamodb:LeadingKeys")
.formParam("ContextEntries.member.1.ContextKeyValues.member.1", "USER_bob")
.formParam("ContextEntries.member.1.ContextKeyValues.member.2", "USER_alice")
.header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20260904/us-east-1/iam/aws4_request")
.when()
.post("/")
.then()
.statusCode(200)
.body("SimulatePrincipalPolicyResponse.SimulatePrincipalPolicyResult.EvaluationResults"
+ ".member.find { it.EvalActionName == 'dynamodb:GetItem' }.EvalDecision",
equalTo("allowed"));
}
}
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.services.iam.model.CallerContext;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -101,4 +102,184 @@ class IamPolicyEvaluatorTest {
assertEquals(Decision.ALLOW,
evaluator.evaluate(caller, null, "s3:GetObject", "*", null));
}
@Test
void singleValuedConditionKeyStillMatchesUnderTheMultiValuedContext() {
// A plain (non-set) operator against a one-element list keeps today's semantics:
// the first value is compared against the OR of the policy's condition values.
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject","Resource":"*",
"Condition":{"StringEquals":{"aws:PrincipalArn":"arn:aws:iam::111122223333:user/alice"}}}
]}""";
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(
List.of(policy), "s3:GetObject", "arn:aws:s3:::bucket/key",
Map.of("aws:PrincipalArn", List.of("arn:aws:iam::111122223333:user/alice"))));
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
List.of(policy), "s3:GetObject", "arn:aws:s3:::bucket/key",
Map.of("aws:PrincipalArn", List.of("arn:aws:iam::111122223333:user/bob"))));
}
private static final String LEADING_KEYS_FOR_ALL = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
"Condition":{"ForAllValues:StringLike":{"dynamodb:LeadingKeys":["USER_alice*"]}}}
]}""";
@Test
void forAllValuesRequiresEveryContextValueToMatch() {
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(
List.of(LEADING_KEYS_FOR_ALL), "dynamodb:GetItem", "*",
Map.of("dynamodb:LeadingKeys", List.of("USER_alice"))));
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
List.of(LEADING_KEYS_FOR_ALL), "dynamodb:GetItem", "*",
Map.of("dynamodb:LeadingKeys", List.of("USER_bob"))));
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(
List.of(LEADING_KEYS_FOR_ALL), "dynamodb:GetItem", "*",
Map.of("dynamodb:LeadingKeys", List.of("USER_alice", "USER_alice_2"))));
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
List.of(LEADING_KEYS_FOR_ALL), "dynamodb:GetItem", "*",
Map.of("dynamodb:LeadingKeys", List.of("USER_alice", "USER_bob"))));
}
@Test
void forAnyValueRequiresAtLeastOneContextValueToMatch() {
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
"Condition":{"ForAnyValue:StringEquals":{"dynamodb:LeadingKeys":["USER_alice"]}}}
]}""";
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(
List.of(policy), "dynamodb:GetItem", "*",
Map.of("dynamodb:LeadingKeys", List.of("USER_bob", "USER_alice"))));
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
List.of(policy), "dynamodb:GetItem", "*",
Map.of("dynamodb:LeadingKeys", List.of("USER_bob", "USER_carol"))));
}
@Test
void emptySetMatchesForAllValuesAndNotForAnyValue() {
// AWS: ForAllValues over an empty set is vacuously true; ForAnyValue is false.
String anyValue = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
"Condition":{"ForAnyValue:StringLike":{"dynamodb:LeadingKeys":["USER_alice*"]}}}
]}""";
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(
List.of(LEADING_KEYS_FOR_ALL), "dynamodb:GetItem", "*",
Map.of("dynamodb:LeadingKeys", List.<String>of())));
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
List.of(anyValue), "dynamodb:GetItem", "*",
Map.of("dynamodb:LeadingKeys", List.<String>of())));
}
@Test
void setOperatorWithoutIfExistsFailsClosedWhenTheKeyIsAbsent() {
// The key is absent from the context entirely — not an empty set. A request that
// cannot be proven in scope is treated as out of scope.
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
List.of(LEADING_KEYS_FOR_ALL), "dynamodb:GetItem", "*", Map.of()));
}
@Test
void setOperatorComposesWithIfExists() {
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
"Condition":{"ForAnyValue:StringEqualsIfExists":{"dynamodb:LeadingKeys":["USER_alice"]}}}
]}""";
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(
List.of(policy), "dynamodb:GetItem", "*", Map.of()));
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
List.of(policy), "dynamodb:GetItem", "*",
Map.of("dynamodb:LeadingKeys", List.of("USER_bob"))));
}
@Test
void nullGuardBlocksTheVacuousForAllValuesAllowWhenTheKeyIsAbsent() {
// The idiomatic AWS pairing: ForAllValues plus Null:false so the vacuous
// empty-set truth cannot grant access when the key was never populated.
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
"Condition":{
"ForAllValues:StringLikeIfExists":{"dynamodb:LeadingKeys":["USER_alice*"]},
"Null":{"dynamodb:LeadingKeys":"false"}}}
]}""";
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
List.of(policy), "dynamodb:GetItem", "*", Map.of()));
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(
List.of(policy), "dynamodb:GetItem", "*",
Map.of("dynamodb:LeadingKeys", List.of("USER_alice"))));
}
@Test
void setOperatorPrefixIsMatchedCaseSensitively() {
// AWS spells these exactly "ForAllValues:" / "ForAnyValue:". A different spelling is
// an unknown operator and must not silently behave like the real thing.
String allValues = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
"Condition":{"forallvalues:StringLike":{"dynamodb:LeadingKeys":["USER_alice*"]}}}
]}""";
String anyValue = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
"Condition":{"forAnyValue:StringLike":{"dynamodb:LeadingKeys":["USER_alice*"]}}}
]}""";
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
List.of(allValues), "dynamodb:GetItem", "*",
Map.of("dynamodb:LeadingKeys", List.of("USER_alice"))));
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
List.of(anyValue), "dynamodb:GetItem", "*",
Map.of("dynamodb:LeadingKeys", List.of("USER_alice"))));
}
@Test
void forAllValuesWithANegatedOperatorAndsAcrossThePolicyValues() {
// The deny-list idiom for dynamodb:Attributes: allow only while none of the
// attributes the request touches is one of the forbidden names. AWS ANDs the
// negated match across the listed values; an OR would let "ssn" through as long
// as it differed from "secret".
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
"Condition":{"ForAllValues:StringNotEquals":{"dynamodb:Attributes":["secret","ssn"]}}}
]}""";
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(
List.of(policy), "dynamodb:GetItem", "*",
Map.of("dynamodb:Attributes", List.of("name", "email"))));
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
List.of(policy), "dynamodb:GetItem", "*",
Map.of("dynamodb:Attributes", List.of("name", "ssn"))));
}
@Test
void nullTreatsAPresentButEmptySetAsAbsent() {
// Same idiomatic pairing as the key-absent case, but here the key is present with an
// empty set. AWS treats an empty-set key as nonexistent for Null, so the Null:false
// guard must still block the vacuous ForAllValues allow.
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
"Condition":{
"ForAllValues:StringLike":{"dynamodb:LeadingKeys":["USER_alice*"]},
"Null":{"dynamodb:LeadingKeys":"false"}}}
]}""";
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
List.of(policy), "dynamodb:GetItem", "*",
Map.of("dynamodb:LeadingKeys", List.of())));
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(
List.of(policy), "dynamodb:GetItem", "*",
Map.of("dynamodb:LeadingKeys", List.of("USER_alice"))));
}
}