fix(iam): enforce inline role policy quota (#5327)

* fix(iam): enforce inline role policy quota

Reject role policy updates that exceed the aggregate non-whitespace
quota without changing previously accepted policies, including concurrent
writes and policies restored after a restart.

* fix(cloudformation): rename role policies within quota

* test(iam): share inline policy fixtures

---------

Co-authored-by: Jason van Zyl <jason@vanzyl.ca>
This commit is contained in:
David PhillipsandJason van Zyl authored and GitHub committed 2026-10-08 21:52:36 -04:00
1 parent da6a7dd085
commit d22b4f107c
8 files changed
+333 -29

No files matched your search

@@ -6,6 +6,7 @@ import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* End-to-end check that CloudFormation applies the inline {@code Policies} of an
@@ -21,6 +22,43 @@ class CloudFormationIamRoleInlinePoliciesIntegrationTest {
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/iam/aws4_request";
@Test
void updateStackRenamesLargeInlinePolicyWithoutExceedingQuota() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-policy-quota-" + suffix;
String roleName = "cfn-policy-quota-role-" + suffix;
String template = """
{"Resources":{"AppRole":{"Type":"AWS::IAM::Role","Properties":{
"RoleName":"%s","AssumeRolePolicyDocument":{"Statement":[]},
"Policies":[{"PolicyName":"%%s","PolicyDocument":{"Statement":[{
"Effect":"Allow","Action":"s3:GetObject","Resource":"*","Sid":"%s"
}]}}]}}}}
""".formatted(roleName, "x".repeat(6_000));
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", template.formatted("old-policy"))
.formParam("Capabilities.member.1", "CAPABILITY_NAMED_IAM")
.post("/").then().statusCode(200);
try {
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName, CFN_AUTH).status());
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack").formParam("StackName", stackName)
.formParam("TemplateBody", template.formatted("new-policy"))
.formParam("Capabilities.member.1", "CAPABILITY_NAMED_IAM")
.post("/").then().statusCode(200);
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName, CFN_AUTH).status());
given().contentType("application/x-www-form-urlencoded").header("Authorization", IAM_AUTH)
.formParam("Action", "ListRolePolicies").formParam("RoleName", roleName)
.post("/").then().statusCode(200)
.body(containsString("new-policy")).body(not(containsString("old-policy")));
} finally {
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DeleteStack").formParam("StackName", stackName)
.post("/").then().statusCode(200);
CfnStackWaits.awaitStackDeleted(stackName);
}
}
@Test
void createStackProvisionsInlineRolePoliciesAndDeleteStackRemovesRole() {
String suffix = Long.toString(System.nanoTime(), 36);
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplate
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.testutil.IamServiceTestHelper;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
@@ -291,6 +292,28 @@ class IamRoleCfnProvisionerTest {
verify(iam, never()).deleteRolePolicy(anyString(), anyString());
}
@Test
void failedPolicyRenameRestoresOriginalPoliciesWithinQuota() throws Exception {
IamService realIam = IamServiceTestHelper.iamServiceWithUserPolicy("test", "secret", "user", EMPTY_TRUST);
IamRoleCfnProvisioner realProvisioner = new IamRoleCfnProvisioner(realIam);
StackResource r = resource();
String policy = "{\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\","
+ "\"Resource\":\"*\",\"Sid\":\"" + "x".repeat(6_000) + "\"}]}";
JsonNode original = mapper.readTree("{\"RoleName\":\"app-role\",\"Policies\":["
+ "{\"PolicyName\":\"old\",\"PolicyDocument\":" + policy + "}]}");
realProvisioner.provision(r, original, ctx());
JsonNode replacement = mapper.readTree("{\"RoleName\":\"app-role\",\"Policies\":["
+ "{\"PolicyName\":\"new\",\"PolicyDocument\":" + policy + "},"
+ "{\"PolicyName\":\"overflow\",\"PolicyDocument\":" + policy + "}]}");
AwsException failure = assertThrows(AwsException.class,
() -> realProvisioner.provision(r, replacement, ctx()));
assertEquals("LimitExceeded", failure.getErrorCode());
assertEquals(0, failure.getSuppressed().length);
assertEquals(Map.of("old", policy), realIam.getRole("app-role").getInlinePolicies());
}
@Test
void failedUpdateRestoresTheInlinePolicyItAlreadyOverwrote() {
// An update that adopts an existing role must not keep the permissions a half-applied
@@ -321,8 +344,8 @@ class IamRoleCfnProvisionerTest {
InOrder order = inOrder(iam);
order.verify(iam).putRolePolicy("app-role", "first", EMPTY_TRUST);
order.verify(iam).deleteRolePolicy("app-role", "first");
order.verify(iam).putRolePolicy("app-role", "first", priorDocument);
verify(iam, never()).deleteRolePolicy(anyString(), anyString());
verify(iam, never()).deleteRole(anyString());
}
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.Totp;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
@@ -27,8 +28,10 @@ import java.time.Instant;
import java.util.List;
import java.util.Map;
import static io.github.hectorvent.floci.services.iam.InlinePolicyTestHelper.policyWithNonWhitespaceLength;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -42,6 +45,32 @@ class IamServicePersistenceTest {
"https://oidc.eks.eu-central-1.amazonaws.com/id/PERSISTED0EXAMPLE";
private static final String THUMBPRINT = "9e99a48a9960b14926bb7f3b02e22da2b0ab7280";
@Test
void roleInlinePolicyQuotaUsesPersistedAggregateAfterRestart(@TempDir Path directory) {
IamService first = newService(directory);
first.createRole("R", "/", "{}", null, 0, null);
String firstPolicy = policyWithNonWhitespaceLength(6_000);
String secondPolicy = policyWithNonWhitespaceLength(4_000);
first.putRolePolicy("R", "first", firstPolicy);
first.putRolePolicy("R", "second", secondPolicy);
IamService restarted = newService(directory);
assertEquals(firstPolicy, restarted.getRolePolicy("R", "first"));
assertEquals(secondPolicy, restarted.getRolePolicy("R", "second"));
AwsException aggregateError = assertThrows(AwsException.class,
() -> restarted.putRolePolicy("R", "third", policyWithNonWhitespaceLength(241)));
assertEquals("LimitExceeded", aggregateError.getErrorCode());
assertEquals(409, aggregateError.getHttpStatus());
AwsException replacementError = assertThrows(AwsException.class,
() -> restarted.putRolePolicy("R", "first", policyWithNonWhitespaceLength(6_241)));
assertEquals("LimitExceeded", replacementError.getErrorCode());
assertEquals(409, replacementError.getHttpStatus());
assertEquals(firstPolicy, restarted.getRolePolicy("R", "first"));
assertEquals(secondPolicy, restarted.getRolePolicy("R", "second"));
}
@Test
void openIdConnectProviderSurvivesRestart(@TempDir Path dir) {
IamService first = newService(dir);
@@ -34,7 +34,13 @@ import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static io.github.hectorvent.floci.services.iam.InlinePolicyTestHelper.policyWithNonWhitespaceLength;
import static org.junit.jupiter.api.Assertions.*;
class IamServiceTest {
@@ -75,6 +81,66 @@ class IamServiceTest {
);
}
@Test
void roleInlinePolicyQuotaIgnoresWhitespaceAndPreservesRejectedReplacement() {
iamService.createRole("R", "/", "{}", null, 0, null);
String exactLimit = policyWithNonWhitespaceLength(10_240);
String padded = exactLimit.substring(0, 1) + " \n\t\r ".repeat(1_000) + exactLimit.substring(1);
iamService.putRolePolicy("R", "inline-exec", padded);
AwsException error = assertThrows(AwsException.class,
() -> iamService.putRolePolicy("R", "inline-exec", policyWithNonWhitespaceLength(10_241)));
assertEquals("LimitExceeded", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
assertEquals(padded, iamService.getRolePolicy("R", "inline-exec"));
}
@Test
void roleInlinePolicyQuotaCountsAllPolicies() {
iamService.createRole("R", "/", "{}", null, 0, null);
iamService.putRolePolicy("R", "first", policyWithNonWhitespaceLength(6_000));
iamService.putRolePolicy("R", "second", policyWithNonWhitespaceLength(4_041));
AwsException error = assertThrows(AwsException.class,
() -> iamService.putRolePolicy("R", "third", policyWithNonWhitespaceLength(200)));
assertEquals("LimitExceeded", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
assertEquals(List.of("first", "second"), iamService.listRolePolicies("R").stream().sorted().toList());
}
@Test
void roleInlinePolicyQuotaIsAtomicAcrossConcurrentWrites() throws Exception {
iamService.createRole("R", "/", "{}", null, 0, null);
CountDownLatch start = new CountDownLatch(1);
AtomicInteger accepted = new AtomicInteger();
AtomicInteger rejected = new AtomicInteger();
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
for (String policyName : List.of("first", "second")) {
executor.submit(() -> {
start.await();
try {
iamService.putRolePolicy("R", policyName, policyWithNonWhitespaceLength(6_000));
accepted.incrementAndGet();
} catch (AwsException error) {
assertEquals("LimitExceeded", error.getErrorCode());
rejected.incrementAndGet();
}
return null;
});
}
start.countDown();
executor.shutdown();
assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
}
assertEquals(1, accepted.get());
assertEquals(1, rejected.get());
assertEquals(1, iamService.listRolePolicies("R").size());
}
/** The STS global endpoint, and so the token version it reports, exists only in the commercial partition. */
@Test
void accountSummaryReportsTheGlobalEndpointTokenVersionOnlyWhereStsHasAGlobalHost() {
@@ -0,0 +1,12 @@
package io.github.hectorvent.floci.services.iam;
final class InlinePolicyTestHelper {
private InlinePolicyTestHelper() {}
static String policyWithNonWhitespaceLength(int targetLength) {
String prefix = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"";
String suffix = "\",\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";
return prefix + "x".repeat(targetLength - prefix.length() - suffix.length()) + suffix;
}
}