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

@@ -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"))));
}
}