fix(iam): match absent context keys with ForAllValues (#5482)

* fix(iam): match absent context keys with ForAllValues

* fix(iam): preserve condition guards for missing keys

* fix(iam): reject unsupported condition shortcuts

* docs(iam): clarify supported IfExists conditions

* fix(iam): enforce requested keys in set conditions

* docs(iam): clarify unresolved attribute conditions

* fix(iam): enforce requested S3 object tag keys

* fix(iam): scope object tag keys to the authorized action
This commit is contained in:
David Phillips authored and GitHub committed 2026-10-12 06:54:16 -04:00
1 parent 6e38c080fb
commit ea8da22226
12 files changed
+655 -69

No files matched your search

@@ -26,9 +26,11 @@ import org.mockito.ArgumentCaptor;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -92,6 +94,7 @@ class IamConditionContextResolverTest {
UriInfo uriInfo = mock(UriInfo.class);
when(containerRequest.getUriInfo()).thenReturn(uriInfo);
when(uriInfo.getPath()).thenReturn(path);
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
when(containerRequest.getEntityStream())
.thenReturn(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));
return containerRequest;
@@ -149,6 +152,55 @@ class IamConditionContextResolverTest {
assertNull(resolver.resolve("s3", "s3:GetObject", containerRequest));
}
@Test
void objectTagKeysDecodeHeadersAndRetainCaseWithoutDuplicates() {
ContainerRequestContext request = s3Request("/bucket/object", "");
when(request.getHeaderString("x-amz-tagging"))
.thenReturn("%54eam=one&Team=two&team=three&Cost%20Center=four&bad=%zz");
Map<String, List<String>> conditions = resolver.resolve("s3", "s3:PutObject", request);
assertEquals(List.of("Team", "team", "Cost Center"), conditions.get("s3:RequestObjectTagKeys"));
assertEquals(List.of("two"), conditions.get("s3:RequestObjectTag/Team"));
assertFalse(conditions.containsKey("s3:RequestObjectTag/bad"));
}
@Test
void queryObjectTagKeysUseHeaderPrecedenceIncludingAnEmptyHeader() {
ContainerRequestContext request = s3Request("/bucket/object", "");
request.getUriInfo().getQueryParameters().putSingle("x-amz-tagging", "%54eam=payments");
Map<String, List<String>> query = resolver.resolve("s3", "s3:PutObject", request);
assertEquals(List.of("Team"), query.get("s3:RequestObjectTagKeys"));
assertEquals(List.of("payments"), query.get("s3:RequestObjectTag/Team"));
when(request.getHeaderString("x-amz-tagging")).thenReturn("Other=value");
assertEquals(List.of("Other"), resolver.resolve("s3", "s3:PutObject", request)
.get("s3:RequestObjectTagKeys"));
when(request.getHeaderString("x-amz-tagging")).thenReturn("");
assertNull(resolver.resolve("s3", "s3:PutObject", request));
}
@Test
void objectTagKeysComeOnlyFromTheRequestedXmlTags() {
ContainerRequestContext request = s3Request("/bucket/object",
"<Tagging><TagSet><Tag><Key>Team</Key><Value>payments</Value></Tag>"
+ "<Tag><Key>Cost&amp;Center</Key><Value>42</Value></Tag></TagSet></Tagging>");
when(request.getUriInfo().getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
when(s3Service.getObjectTagging("bucket", "object", null)).thenReturn(Map.of("Previous", "old"));
Map<String, List<String>> conditions = resolver.resolve("s3", "s3:PutObjectTagging", request);
assertEquals(Set.of("Team", "Cost&Center"), new HashSet<>(conditions.get("s3:RequestObjectTagKeys")));
assertEquals(List.of("old"), conditions.get("s3:ExistingObjectTag/Previous"));
assertEquals(List.of("42"), conditions.get("s3:RequestObjectTag/Cost&Center"));
}
@Test
void emptyObjectTagRequestsDoNotExposeRequestedKeys() {
assertNull(resolver.resolve("s3", "s3:PutObject", s3Request("/bucket/object", "")));
ContainerRequestContext empty = s3Request("/bucket/object", "<Tagging><TagSet/></Tagging>");
when(empty.getUriInfo().getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
when(s3Service.getObjectTagging("bucket", "object", null)).thenReturn(Map.of("Previous", "old"));
Map<String, List<String>> conditions = resolver.resolve("s3", "s3:PutObjectTagging", empty);
assertEquals(List.of("old"), conditions.get("s3:ExistingObjectTag/Previous"));
assertFalse(conditions.containsKey("s3:RequestObjectTagKeys"));
}
@Test
void resolvesDynamoDbLeadingKeysForGetItem() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
@@ -220,19 +272,25 @@ class IamConditionContextResolverTest {
}
@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.
void resolvesEachBatchTableWithItsOwnSchema() {
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"}}]}}}"""));
"OtherTable":{"Keys":[{"Tenant":{"S":"USER_bob"}}]}}}"""));
TableDefinition other = new TableDefinition();
other.setTableName("OtherTable");
other.setKeySchema(List.of(new KeySchemaElement("Tenant", "HASH")));
when(dynamoDbService.findTable("FgacTable", "us-east-1")).thenReturn(Optional.of(fgacTable()));
when(dynamoDbService.findTable("OtherTable", "us-east-1")).thenReturn(Optional.of(other));
Map<String, List<String>> conditions =
resolver.resolve("dynamodb", "dynamodb:BatchGetItem", containerRequest);
assertFalse(conditions.containsKey("dynamodb:LeadingKeys"));
assertEquals(List.of("USER_alice", "USER_bob"), conditions.get("dynamodb:LeadingKeys"));
assertEquals(List.of("USER_bob"), resolver.dynamoDbBatchConditionContext(
"dynamodb:BatchGetItem", containerRequest,
"arn:aws:dynamodb:us-east-1:000000000000:table/OtherTable").get("dynamodb:LeadingKeys"));
}
// ── aws:RequestTag and aws:ResourceTag ─────────────────────────────────────
@@ -249,6 +307,7 @@ class IamConditionContextResolverTest {
assertEquals(List.of("payments"), conditions.get("aws:RequestTag/Team"));
assertEquals(List.of("prod"), conditions.get("aws:RequestTag/Env"));
assertEquals(Set.of("Team", "Env"), new HashSet<>(conditions.get("aws:TagKeys")));
}
@Test
@@ -295,6 +354,7 @@ class IamConditionContextResolverTest {
assertEquals(List.of("payments"), conditions.get("aws:RequestTag/Team"));
assertEquals(List.of("prod"), conditions.get("aws:RequestTag/Env"));
assertEquals(List.of("Team", "Env"), conditions.get("aws:TagKeys"));
assertFalse(conditions.containsKey("aws:ResourceTag/Team"));
}
@@ -6,6 +6,9 @@ import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.UUID;
@@ -88,9 +91,8 @@ class DynamoDbFgacEnforcementIntegrationTest {
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.
// The Key omits the partition attribute, so the leading key cannot be resolved.
// The session policy's Null:false guard denies it before DynamoDB handles the request.
given()
.header("Authorization", auth(accessKeyId, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20120810.GetItem")
@@ -155,6 +157,115 @@ class DynamoDbFgacEnforcementIntegrationTest {
.body(containsString("AccessDeniedException"));
}
@ParameterizedTest
@ValueSource(strings = {":uid = PK", ":uid = #pk"})
void reversedQueryRequiresTheRequestedPartitionWithoutNullGuard(String expression) {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String table = "fgac-reversed-" + suffix;
String role = "FgacReversed" + suffix;
createTable(table);
putItem(table, "USER_alice");
putItem(table, "USER_bob");
createRole(role);
putBroadDynamoDbRolePolicy(role);
String accessKey = assumeRoleWithLeadingKeysSessionPolicy(role, false);
for (String user : new String[]{"USER_alice", "USER_bob"}) {
given().header("Authorization", auth(accessKey, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20120810.Query")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"TableName":"%s","KeyConditionExpression":"%s",%s
"ExpressionAttributeValues":{":uid":{"S":"%s"}}}
""".formatted(table, expression, expression.contains("#")
? "\"ExpressionAttributeNames\":{\"#pk\":\"PK\"}," : "", user))
.post("/").then().statusCode(user.equals("USER_alice") ? 200 : 400)
.body(containsString(user.equals("USER_alice") ? "USER_alice" : "AccessDeniedException"));
}
}
@ParameterizedTest
@CsvSource({"BatchGetItem,false", "BatchGetItem,true", "BatchWriteItem,false", "BatchWriteItem,true"})
void everyBatchEntryContributesLeadingKeysWithoutNullGuard(String action, boolean alias) {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String table = "fgac-batch-" + suffix;
String other = alias ? "arn:aws:dynamodb:" + REGION + ":" + ROLE_ACCOUNT_ID + ":table/" + table
: "fgac-other-" + suffix;
String role = "FgacBatch" + suffix;
createTable(table);
if (!alias) {
createTable(other);
}
putItem(table, "USER_alice");
putItem(other, "USER_bob");
createRole(role);
putBroadDynamoDbRolePolicy(role);
String accessKey = assumeRoleWithLeadingKeysSessionPolicy(role, false);
for (String user : new String[]{"USER_alice_2", "USER_bob"}) {
String first = batchEntry(action, "USER_alice");
String second = batchEntry(action, user);
given().header("Authorization", auth(accessKey, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20120810." + action)
.contentType(DYNAMODB_CONTENT_TYPE)
.body("{\"RequestItems\":{\"" + table + "\":" + first + ",\"" + other + "\":" + second + "}}")
.post("/").then().statusCode(user.equals("USER_bob") ? 400 : 200)
.body(containsString(user.equals("USER_bob") ? "AccessDeniedException"
: action.equals("BatchGetItem") ? "Responses" : "UnprocessedItems"));
}
given().header("Authorization", auth(ROLE_ACCOUNT_ID, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20120810.GetItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("{\"TableName\":\"" + other + "\",\"Key\":{\"PK\":{\"S\":\"USER_bob\"}}}")
.post("/").then().statusCode(200).body("Item.PK.S", equalTo("USER_bob"));
}
@Test
void batchPoliciesEvaluateEachTableWithOnlyItsOwnKeys() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String first = "fgac-first-" + suffix;
String second = "fgac-second-" + suffix;
String role = "FgacSeparate" + suffix;
createTable(first);
createTable(second);
putItem(first, "USER_alice");
putItem(second, "USER_bob");
createRole(role);
String statements = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:BatchGetItem","Resource":"%s",
"Condition":{"ForAllValues:StringEquals":{"dynamodb:LeadingKeys":["USER_alice"]}}},
{"Effect":"Allow","Action":"dynamodb:BatchGetItem","Resource":"%s",
"Condition":{"ForAllValues:StringEquals":{"dynamodb:LeadingKeys":["USER_bob"]}}}]}
""".formatted("arn:aws:dynamodb:" + REGION + ":" + ROLE_ACCOUNT_ID + ":table/" + first,
"arn:aws:dynamodb:" + REGION + ":" + ROLE_ACCOUNT_ID + ":table/" + second);
given().header("Authorization", auth(ROLE_ACCOUNT_ID, "iam"))
.formParam("Action", "PutRolePolicy").formParam("RoleName", role)
.formParam("PolicyName", "Tables").formParam("PolicyDocument", statements)
.post("/").then().statusCode(200);
String accessKey = given().header("Authorization", auth(CALLER_ACCOUNT_ID, "sts"))
.formParam("Action", "AssumeRole")
.formParam("RoleArn", "arn:aws:iam::" + ROLE_ACCOUNT_ID + ":role/" + role)
.formParam("RoleSessionName", "separate-tables")
.post("/").then().statusCode(200).extract()
.path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId");
for (boolean swapped : new boolean[]{false, true}) {
given().header("Authorization", auth(accessKey, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20120810.BatchGetItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("{\"RequestItems\":{\"" + first + "\":"
+ batchEntry("BatchGetItem", swapped ? "USER_bob" : "USER_alice")
+ ",\"" + second + "\":"
+ batchEntry("BatchGetItem", swapped ? "USER_alice" : "USER_bob") + "}}")
.post("/").then().statusCode(swapped ? 400 : 200)
.body(containsString(swapped ? "AccessDeniedException" : "USER_bob"));
}
}
private static String batchEntry(String action, String user) {
String key = "{\"PK\":{\"S\":\"" + user + "\"}}";
return action.equals("BatchGetItem") ? "{\"Keys\":[" + key + "]}"
: "[{\"DeleteRequest\":{\"Key\":" + key + "}}]";
}
private static void createTable(String tableName) {
given()
.header("Authorization", auth(ROLE_ACCOUNT_ID, "dynamodb"))
@@ -272,16 +383,21 @@ class DynamoDbFgacEnforcementIntegrationTest {
* allow or a deny can only come from the LeadingKeys condition.
*/
private static String assumeRoleWithLeadingKeysSessionPolicy(String roleName) {
return assumeRoleWithLeadingKeysSessionPolicy(roleName, true);
}
private static String assumeRoleWithLeadingKeysSessionPolicy(String roleName, boolean nullGuard) {
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:*","Resource":"*",
"Condition":{"ForAllValues:StringLike":{"dynamodb:LeadingKeys":["USER_alice*"]}%s}}
]}
""".formatted(nullGuard ? ",\"Null\":{\"dynamodb:LeadingKeys\":\"false\"}" : "");
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*"]}}}
]}""")
.formParam("Policy", policy)
.header("Authorization", auth(CALLER_ACCOUNT_ID, "sts"))
.when()
.post("/")
@@ -219,7 +219,8 @@ class IamEnforcementIntegrationTest {
{"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*"]}}}
"Condition":{"ForAllValues:StringLike":{"dynamodb:LeadingKeys":["USER_alice*"]},
"Null":{"dynamodb:LeadingKeys":"false"}}}
]}""";
@Test
@@ -234,7 +235,7 @@ class IamEnforcementIntegrationTest {
"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.
// Null:false requires a leading key even though ForAllValues alone would match.
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
List.of(LEADING_KEYS_SCOPED_POLICY), "dynamodb:GetItem",
"arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable",
@@ -7,6 +7,7 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.LinkedHashMap;
@@ -421,6 +422,51 @@ class IamIntegrationTest {
equalTo("implicitDeny"));
}
@ParameterizedTest
@CsvSource({
"ForAllValues:StringLike, allowed",
"ForAllValues:StringNotLike, allowed",
"ForAnyValue:StringLike, implicitDeny",
"ForAnyValue:StringNotLike, implicitDeny"
})
void simulateCustomPolicyUsesSetOperatorSemanticsForMissingKeys(String operator, String decision) {
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
"Condition":{"%s":{"dynamodb:LeadingKeys":["USER_alice*"]}}}
]}""".formatted(operator);
given()
.formParam("Action", "SimulateCustomPolicy")
.formParam("PolicyInputList.member.1", policy)
.formParam("ActionNames.member.1", "dynamodb:GetItem")
.formParam("ResourceArns.member.1", "*")
.header("Authorization", IAM_AUTH)
.when().post("/").then().statusCode(200)
.body("SimulateCustomPolicyResponse.SimulateCustomPolicyResult.EvaluationResults.member.EvalDecision",
equalTo(decision));
}
@ParameterizedTest
@ValueSource(strings = {"ForAllValues:StringTypoIfExists", "ForAnyValue:StringTypoIfExists",
"StringTypoIfExists", "ForAllValues:Null", "ForAnyValue:Null", "NullIfExists",
"ForAllValues:NullIfExists", "ForAnyValue:NullIfExists"})
void simulateCustomPolicyRejectsUnsupportedMissingKeyShortcuts(String operator) {
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
"Condition":{"%s":{"dynamodb:LeadingKeys":["true"]}}}
]}""".formatted(operator);
given()
.formParam("Action", "SimulateCustomPolicy")
.formParam("PolicyInputList.member.1", policy)
.formParam("ActionNames.member.1", "dynamodb:GetItem")
.formParam("ResourceArns.member.1", "*")
.header("Authorization", IAM_AUTH)
.when().post("/").then().statusCode(200)
.body("SimulateCustomPolicyResponse.SimulateCustomPolicyResult.EvaluationResults.member.EvalDecision",
equalTo("implicitDeny"));
}
@Test
@Order(37)
void simulateCustomPolicyAppliesPermissionsBoundary() {
@@ -7,6 +7,8 @@ import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourceAccoun
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.time.Duration;
import java.util.List;
@@ -396,11 +398,81 @@ class IamPolicyEvaluatorTest {
}
@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(
void forAllValuesMatchesWhenTheKeyIsAbsent() {
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(
List.of(LEADING_KEYS_FOR_ALL), "dynamodb:GetItem", "*", Map.of()));
assertEquals(Decision.ALLOW, evaluator.evaluate(CallerContext.of(List.of(LEADING_KEYS_FOR_ALL)),
List.of(), "dynamodb:GetItem", "*", Map.of()));
}
@Test
void forAllValuesExplicitDenyMatchesWhenTheKeyIsAbsent() {
String deny = LEADING_KEYS_FOR_ALL.replace("\"Effect\":\"Allow\"", "\"Effect\":\"Deny\"");
assertEquals(Decision.DENY, evaluator.evaluate(CallerContext.of(List.of(ALLOW_ALL, deny)),
List.of(), "dynamodb:GetItem", "*", Map.of()));
assertEquals(IamPolicyEvaluator.SimulationDecision.EXPLICIT_DENY, evaluator.simulatePrincipalPolicy(
CallerContext.of(List.of(ALLOW_ALL, deny)), "dynamodb:GetItem", "*", Map.of()));
}
@Test
void forAllValuesMissingKeyStillRequiresOtherConditionKeysToMatch() {
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
"Condition":{"ForAllValues:StringLike":{
"dynamodb:LeadingKeys":["USER_alice*"],"aws:TagKeys":["environment"]}}}
]}""";
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy), "dynamodb:GetItem", "*",
Map.of("aws:TagKeys", List.of("unapproved"))));
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(List.of(policy), "dynamodb:GetItem", "*",
Map.of("aws:TagKeys", List.of("environment"))));
}
@Test
void unknownForAllValuesOperatorsDoNotMatchMissingKeys() {
for (String operator : List.of("ForAllValues:StringTypo", "ForAllValues:ForAnyValue:StringLike")) {
String allow = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
"Condition":{"%s":{"dynamodb:LeadingKeys":["USER_alice*"]}}}
]}""".formatted(operator);
String deny = allow.replace("\"Effect\":\"Allow\"", "\"Effect\":\"Deny\"");
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
List.of(allow), "dynamodb:GetItem", "*", Map.of()));
assertEquals(Decision.DENY, evaluator.evaluate(CallerContext.of(List.of(allow)),
List.of(), "dynamodb:GetItem", "*", Map.of()));
assertEquals(IamPolicyEvaluator.SimulationDecision.ALLOWED, evaluator.simulatePrincipalPolicy(
CallerContext.of(List.of(ALLOW_ALL, deny)), "dynamodb:GetItem", "*", Map.of()));
assertEquals(Decision.ALLOW, evaluator.evaluate(CallerContext.of(List.of(ALLOW_ALL, deny)),
List.of(), "dynamodb:GetItem", "*", Map.of()));
}
}
@ParameterizedTest
@ValueSource(strings = {"ForAllValues:StringTypoIfExists", "ForAnyValue:StringTypoIfExists",
"StringTypoIfExists", "ForAllValues:Null", "ForAnyValue:Null", "NullIfExists",
"ForAllValues:NullIfExists", "ForAnyValue:NullIfExists"})
void unsupportedOperatorsCannotBypassConditionChecks(String operator) {
String allow = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
"Condition":{"%s":{"dynamodb:LeadingKeys":["true"]}}}
]}""".formatted(operator);
String deny = allow.replace("\"Effect\":\"Allow\"", "\"Effect\":\"Deny\"");
List<Map<String, List<String>>> contexts = List.of(Map.of(),
Map.of("dynamodb:LeadingKeys", List.of()),
Map.of("dynamodb:LeadingKeys", List.of("USER_alice")));
for (Map<String, List<String>> context : contexts) {
assertFalse(IamPolicyEvaluator.isSupportedConditionOperator(operator));
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
List.of(allow), "dynamodb:GetItem", "*", context));
assertEquals(Decision.DENY, evaluator.evaluate(CallerContext.of(List.of(allow)),
List.of(), "dynamodb:GetItem", "*", context));
assertEquals(IamPolicyEvaluator.SimulationDecision.ALLOWED, evaluator.simulatePrincipalPolicy(
CallerContext.of(List.of(ALLOW_ALL, deny)), "dynamodb:GetItem", "*", context));
assertEquals(Decision.ALLOW, evaluator.evaluate(CallerContext.of(List.of(ALLOW_ALL, deny)),
List.of(), "dynamodb:GetItem", "*", context));
}
}
@Test
@@ -426,7 +498,7 @@ class IamPolicyEvaluatorTest {
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
"Condition":{
"ForAllValues:StringLikeIfExists":{"dynamodb:LeadingKeys":["USER_alice*"]},
"ForAllValues:StringLike":{"dynamodb:LeadingKeys":["USER_alice*"]},
"Null":{"dynamodb:LeadingKeys":"false"}}}
]}""";
@@ -0,0 +1,199 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.net.URI;
import java.util.UUID;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.createUser;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.removeBucket;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class IamTagKeysEnforcementIntegrationTest {
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@TestHTTPResource
URI endpoint;
@Test
void ec2CreateTagsRejectsAnUnlistedKeyWithoutNullGuard() {
String id = given().header("Authorization", auth("test", "ec2"))
.formParam("Action", "CreateVpc").formParam("CidrBlock", "10.89.0.0/16")
.post("/").then().statusCode(200).extract().path("CreateVpcResponse.vpc.vpcId");
int port = endpoint.getPort();
cleanup.register(() -> given().port(port).header("Authorization", auth("test", "ec2"))
.formParam("Action", "DeleteVpc").formParam("VpcId", id).post("/"));
String key = scopedUser("ec2:CreateTags", "aws:TagKeys");
given().header("Authorization", auth(key, "ec2"))
.formParam("Action", "CreateTags").formParam("ResourceId.1", id)
.formParam("Tag.1.Key", "Team").formParam("Tag.1.Value", "payments")
.post("/").then().statusCode(200);
given().header("Authorization", auth(key, "ec2"))
.formParam("Action", "CreateTags").formParam("ResourceId.1", id)
.formParam("Tag.1.Key", "Team").formParam("Tag.1.Value", "payments")
.formParam("Tag.2.Key", "Admin").formParam("Tag.2.Value", "true")
.post("/").then().statusCode(403).body(containsString("AccessDenied"));
}
@Test
void s3BucketTaggingRejectsAnUnlistedKeyWithoutNullGuard() {
String bucket = bucket();
String key = scopedUser("s3:PutBucketTagging", "aws:TagKeys");
String allowed = "<Tag><Key>Team</Key><Value>payments</Value></Tag>";
given().header("Authorization", auth(key, "s3")).queryParam("tagging", "")
.body("<Tagging><TagSet>" + allowed + "</TagSet></Tagging>")
.put("/" + bucket).then().statusCode(204);
given().header("Authorization", auth(key, "s3")).queryParam("tagging", "")
.body("<Tagging><TagSet>" + allowed
+ "<Tag><Key>Admin</Key><Value>true</Value></Tag></TagSet></Tagging>")
.put("/" + bucket).then().statusCode(403).body(containsString("AccessDenied"));
}
@ParameterizedTest
@ValueSource(strings = {"Admin", "team"})
void s3ObjectUploadRestrictsAllRequestedKeysWithoutNullGuard(String forbiddenKey) {
String bucket = bucket();
String key = scopedUser("s3:PutObject", "s3:RequestObjectTagKeys");
String path = "/" + bucket + "/object";
given().header("Authorization", auth(key, "s3")).header("x-amz-tagging", "%54eam=payments")
.body("original").put(path).then().statusCode(200);
given().header("Authorization", auth(key, "s3"))
.header("x-amz-tagging", "Team=payments&" + forbiddenKey + "=true")
.body("forbidden replacement").put(path).then().statusCode(403)
.body(containsString("AccessDenied"));
given().header("Authorization", auth("test", "s3")).get(path)
.then().statusCode(200).body(equalTo("original"));
given().header("Authorization", auth("test", "s3")).queryParam("tagging", "").get(path)
.then().statusCode(200).body(containsString("<Key>Team</Key>"))
.body(not(containsString("<Key>" + forbiddenKey + "</Key>")));
// No tags retain the vacuous ForAllValues match; there is no Null guard.
given().header("Authorization", auth(key, "s3")).body("untagged").put(path)
.then().statusCode(200);
}
@ParameterizedTest
@ValueSource(strings = {"Admin", "team"})
void s3ObjectTaggingRestrictsAllRequestedKeysWithoutNullGuard(String forbiddenKey) {
String bucket = bucket();
String path = "/" + bucket + "/object";
given().header("Authorization", auth("test", "s3")).body("original").put(path)
.then().statusCode(200);
String key = scopedUser("s3:PutObjectTagging", "s3:RequestObjectTagKeys");
String allowed = "<Tag><Key>Team</Key><Value>payments</Value></Tag>";
given().header("Authorization", auth(key, "s3")).queryParam("tagging", "")
.body("<Tagging><TagSet>" + allowed + "</TagSet></Tagging>")
.put(path).then().statusCode(200);
given().header("Authorization", auth(key, "s3")).queryParam("tagging", "")
.body("<Tagging><TagSet>" + allowed + "<Tag><Key>" + forbiddenKey
+ "</Key><Value>true</Value></Tag></TagSet></Tagging>")
.put(path).then().statusCode(403).body(containsString("AccessDenied"));
given().header("Authorization", auth("test", "s3")).queryParam("tagging", "").get(path)
.then().statusCode(200).body(containsString("<Key>Team</Key>"))
.body(not(containsString("<Key>" + forbiddenKey + "</Key>")));
// An empty tag set removes the tags and still matches ForAllValues.
given().header("Authorization", auth(key, "s3")).queryParam("tagging", "")
.body("<Tagging><TagSet/></Tagging>").put(path).then().statusCode(200);
given().header("Authorization", auth("test", "s3")).queryParam("tagging", "").get(path)
.then().statusCode(200).body(not(containsString("<Key>Team</Key>")));
}
@ParameterizedTest
@ValueSource(strings = {"Admin", "team"})
void s3QueryTagKeysAreCheckedBeforeAnUpload(String forbiddenKey) {
String bucket = bucket();
String key = scopedUser("s3:PutObject", "s3:RequestObjectTagKeys");
String path = "/" + bucket + "/object";
given().header("Authorization", auth(key, "s3")).queryParam("x-amz-tagging", "%54eam=payments")
.body("original").put(path).then().statusCode(200);
given().header("Authorization", auth(key, "s3"))
.queryParam("x-amz-tagging", "Team=payments&" + forbiddenKey + "=true")
.body("forbidden").put(path).then().statusCode(403);
given().header("Authorization", auth("test", "s3")).get(path)
.then().statusCode(200).body(equalTo("original"));
given().header("Authorization", auth("test", "s3")).queryParam("tagging", "").get(path)
.then().statusCode(200).body(containsString("<Key>Team</Key>"))
.body(not(containsString("<Key>" + forbiddenKey + "</Key>")));
}
@Test
void s3TagHeaderTakesPrecedenceOverTheQuery() {
String bucket = bucket();
String key = scopedUser("s3:PutObject", "s3:RequestObjectTagKeys");
String path = "/" + bucket + "/object";
given().header("Authorization", auth(key, "s3")).header("x-amz-tagging", "Team=payments")
.queryParam("x-amz-tagging", "Admin=true").body("original").put(path).then().statusCode(200);
given().header("Authorization", auth(key, "s3")).header("x-amz-tagging", "Admin=true")
.queryParam("x-amz-tagging", "Team=payments").body("forbidden").put(path).then().statusCode(403);
given().header("Authorization", auth("test", "s3")).get(path)
.then().statusCode(200).body(equalTo("original"));
given().header("Authorization", auth("test", "s3")).queryParam("tagging", "").get(path)
.then().statusCode(200).body(containsString("<Key>Team</Key>"))
.body(not(containsString("<Key>Admin</Key>")));
}
@Test
void conditionalUploadCannotUseRequestedKeysToGrantReadAccess() {
String bucket = bucket();
String path = "/" + bucket + "/object";
String etag = given().header("Authorization", auth("test", "s3")).body("original")
.put(path).then().statusCode(200).extract().header("ETag");
String key = userWithPolicy("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:PutObject","Resource":"*"},
{"Effect":"Allow","Action":"s3:GetObject","Resource":"*",
"Condition":{"ForAnyValue:StringEquals":{"s3:RequestObjectTagKeys":["Team"]}}}]}
""");
given().header("Authorization", auth(key, "s3")).header("x-amz-tagging", "Team=payments")
.header("If-Match", etag).body("forbidden").put(path).then().statusCode(403);
given().header("Authorization", auth("test", "s3")).get(path)
.then().statusCode(200).body(equalTo("original"));
String allowedKey = userWithPolicy("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":["s3:PutObject","s3:GetObject"],"Resource":"*"}]}
""");
given().header("Authorization", auth(allowedKey, "s3")).header("x-amz-tagging", "Team=payments")
.header("If-Match", etag).body("allowed").put(path).then().statusCode(200);
given().header("Authorization", auth("test", "s3")).get(path)
.then().statusCode(200).body(equalTo("allowed"));
}
private String bucket() {
String bucket = "tagkeys-" + UUID.randomUUID();
int port = endpoint.getPort();
cleanup.register(() -> removeBucket(port, auth("test", "s3"), bucket));
given().header("Authorization", auth("test", "s3")).put("/" + bucket).then().statusCode(200);
return bucket;
}
private String scopedUser(String action, String conditionKey) {
return userWithPolicy("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"%s",
"Resource":"*","Condition":{"ForAllValues:StringEquals":{"%s":["Team"]}}}]}
""".formatted(action, conditionKey));
}
private String userWithPolicy(String policy) {
String user = "tagkeys-" + UUID.randomUUID();
String accessKey = createUser(cleanup, endpoint.getPort(), auth("test", "iam"), user).accessKeyId();
given().header("Authorization", auth("test", "iam"))
.formParam("Action", "PutUserPolicy").formParam("UserName", user).formParam("PolicyName", "tags")
.formParam("PolicyDocument", policy).post("/").then().statusCode(200);
return accessKey;
}
}