mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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:
1 parent
da6a7dd085
commit
d22b4f107c
8 files changed
+333
-29
No files matched your search
+116
@@ -0,0 +1,116 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.iam.IamClient;
|
||||
import software.amazon.awssdk.services.iam.model.CreateRoleRequest;
|
||||
import software.amazon.awssdk.services.iam.model.DeleteRolePolicyRequest;
|
||||
import software.amazon.awssdk.services.iam.model.DeleteRoleRequest;
|
||||
import software.amazon.awssdk.services.iam.model.GetRolePolicyRequest;
|
||||
import software.amazon.awssdk.services.iam.model.LimitExceededException;
|
||||
import software.amazon.awssdk.services.iam.model.ListRolePoliciesRequest;
|
||||
import software.amazon.awssdk.services.iam.model.PutRolePolicyRequest;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
class IamRoleInlinePolicyQuotaTest {
|
||||
|
||||
private static final int ROLE_INLINE_POLICY_QUOTA = 10_240;
|
||||
private static final String TRUST_POLICY = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}
|
||||
""";
|
||||
|
||||
@Test
|
||||
void enforcesAggregateNonWhitespaceQuotaAndPreservesAcceptedPolicies() {
|
||||
String roleName = TestFixtures.uniqueName("sdk-role-inline-quota");
|
||||
String exactLimitPolicy = policyWithNonWhitespaceLength(ROLE_INLINE_POLICY_QUOTA);
|
||||
String whitespacePaddedPolicy = exactLimitPolicy.substring(0, 1)
|
||||
+ " \n\t\r ".repeat(1_000)
|
||||
+ exactLimitPolicy.substring(1);
|
||||
|
||||
try (IamClient iam = TestFixtures.iamClient()) {
|
||||
createRole(iam, roleName);
|
||||
try {
|
||||
putRolePolicy(iam, roleName, "exact-limit", whitespacePaddedPolicy);
|
||||
|
||||
assertThatThrownBy(() -> putRolePolicy(iam, roleName, "exact-limit",
|
||||
policyWithNonWhitespaceLength(ROLE_INLINE_POLICY_QUOTA + 1)))
|
||||
.isInstanceOf(LimitExceededException.class)
|
||||
.satisfies(error -> assertThat(((LimitExceededException) error).statusCode()).isEqualTo(409));
|
||||
|
||||
assertThat(iam.getRolePolicy(GetRolePolicyRequest.builder()
|
||||
.roleName(roleName)
|
||||
.policyName("exact-limit")
|
||||
.build())
|
||||
.policyDocument())
|
||||
.satisfies(readBack -> assertThat(removeCountedWhitespace(readBack)).isEqualTo(exactLimitPolicy));
|
||||
} finally {
|
||||
deleteRolePolicies(iam, roleName);
|
||||
deleteRole(iam, roleName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAggregateQuotaOverflowAcrossPolicies() {
|
||||
String roleName = TestFixtures.uniqueName("sdk-role-inline-aggregate-quota");
|
||||
|
||||
try (IamClient iam = TestFixtures.iamClient()) {
|
||||
createRole(iam, roleName);
|
||||
try {
|
||||
putRolePolicy(iam, roleName, "first", policyWithNonWhitespaceLength(6_000));
|
||||
putRolePolicy(iam, roleName, "second", policyWithNonWhitespaceLength(4_041));
|
||||
|
||||
assertThatThrownBy(() -> putRolePolicy(iam, roleName, "third", policyWithNonWhitespaceLength(200)))
|
||||
.isInstanceOf(LimitExceededException.class)
|
||||
.satisfies(error -> assertThat(((LimitExceededException) error).statusCode()).isEqualTo(409));
|
||||
} finally {
|
||||
deleteRolePolicies(iam, roleName);
|
||||
deleteRole(iam, roleName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void createRole(IamClient iam, String roleName) {
|
||||
iam.createRole(CreateRoleRequest.builder()
|
||||
.roleName(roleName)
|
||||
.assumeRolePolicyDocument(TRUST_POLICY)
|
||||
.build());
|
||||
}
|
||||
|
||||
private static void putRolePolicy(IamClient iam, String roleName, String policyName, String policyDocument) {
|
||||
iam.putRolePolicy(PutRolePolicyRequest.builder()
|
||||
.roleName(roleName)
|
||||
.policyName(policyName)
|
||||
.policyDocument(policyDocument)
|
||||
.build());
|
||||
}
|
||||
|
||||
private static void deleteRolePolicies(IamClient iam, String roleName) {
|
||||
for (String policyName : iam.listRolePolicies(ListRolePoliciesRequest.builder()
|
||||
.roleName(roleName)
|
||||
.build()).policyNames()) {
|
||||
iam.deleteRolePolicy(DeleteRolePolicyRequest.builder()
|
||||
.roleName(roleName)
|
||||
.policyName(policyName)
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
private static void deleteRole(IamClient iam, String roleName) {
|
||||
iam.deleteRole(DeleteRoleRequest.builder().roleName(roleName).build());
|
||||
}
|
||||
|
||||
private 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;
|
||||
}
|
||||
|
||||
private static String removeCountedWhitespace(String policyDocument) {
|
||||
return policyDocument.replace(" ", "")
|
||||
.replace("\t", "")
|
||||
.replace("\n", "")
|
||||
.replace("\r", "");
|
||||
}
|
||||
}
|
||||
+23
-26
@@ -14,6 +14,7 @@ import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -148,6 +149,7 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner {
|
||||
// Inline policies run inside the same protected block: a failure here used to leave
|
||||
// the created role, its managed attachments and any earlier inline writes behind,
|
||||
// because rollback only deletes resources that reached CREATE_COMPLETE.
|
||||
Map<String, String> desiredInlinePolicies = new LinkedHashMap<>();
|
||||
if (props != null && props.has("Policies")) {
|
||||
for (JsonNode policy : props.get("Policies")) {
|
||||
String declaredName = ctx.resolveOptional(policy, "PolicyName");
|
||||
@@ -167,9 +169,7 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner {
|
||||
"Inline policy '" + policyName + "' on role " + resolvedRoleName
|
||||
+ " has no PolicyDocument.", 400);
|
||||
}
|
||||
iamService.putRolePolicy(resolvedRoleName, policyName,
|
||||
ctx.engine().resolveJsonAttributeStrict(document));
|
||||
inlineWrittenByThisAttempt.add(policyName);
|
||||
desiredInlinePolicies.put(policyName, ctx.engine().resolveJsonAttributeStrict(document));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,12 +180,17 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner {
|
||||
// calls raise NoSuchEntity on an absent target, which would fail an update whose desired
|
||||
// end state, the policy not being on the role, already holds.
|
||||
for (String stale : previousInlineNames) {
|
||||
if (!inlineWrittenByThisAttempt.contains(stale)
|
||||
if (!desiredInlinePolicies.containsKey(stale)
|
||||
&& originalInlinePolicies.containsKey(stale)) {
|
||||
iamService.deleteRolePolicy(resolvedRoleName, stale);
|
||||
inlineRemovedByThisAttempt.add(stale);
|
||||
}
|
||||
}
|
||||
// Free the quota held by renamed policies before writing their replacements.
|
||||
for (Map.Entry<String, String> policy : desiredInlinePolicies.entrySet()) {
|
||||
iamService.putRolePolicy(resolvedRoleName, policy.getKey(), policy.getValue());
|
||||
inlineWrittenByThisAttempt.add(policy.getKey());
|
||||
}
|
||||
for (String stale : previousManagedArns) {
|
||||
if (!managedPolicyArns.contains(stale) && originalPolicyArns.contains(stale)) {
|
||||
iamService.detachRolePolicy(resolvedRoleName, stale);
|
||||
@@ -195,19 +200,6 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner {
|
||||
} catch (RuntimeException failure) {
|
||||
boolean cleanupSucceeded = true;
|
||||
|
||||
// Reconciliation runs last, so unwinding it comes first. A policy this attempt took out
|
||||
// because the template stopped declaring it goes back with the document it had.
|
||||
for (String policyName : inlineRemovedByThisAttempt) {
|
||||
String prior = originalInlinePolicies.get(policyName);
|
||||
if (prior == null) {
|
||||
continue;
|
||||
}
|
||||
if (!CfnRollback.attemptIamCleanup(failure,
|
||||
"restore inline policy " + policyName + " on role " + resolvedRoleName,
|
||||
() -> iamService.putRolePolicy(resolvedRoleName, policyName, prior))) {
|
||||
cleanupSucceeded = false;
|
||||
}
|
||||
}
|
||||
for (String policyArn : detachedByThisAttempt) {
|
||||
if (!CfnRollback.attemptIamCleanup(failure,
|
||||
"reattach policy " + policyArn + " to role " + resolvedRoleName,
|
||||
@@ -216,19 +208,24 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
}
|
||||
|
||||
// Remove this attempt's writes before restoring earlier documents, so temporary
|
||||
// overlap cannot exceed the role quota during rollback either.
|
||||
List<String> inlineRollback = new ArrayList<>(inlineWrittenByThisAttempt);
|
||||
Collections.reverse(inlineRollback);
|
||||
for (String policyName : inlineRollback) {
|
||||
if (!CfnRollback.attemptIamCleanup(failure,
|
||||
"remove inline policy " + policyName + " on role " + resolvedRoleName,
|
||||
() -> iamService.deleteRolePolicy(resolvedRoleName, policyName))) {
|
||||
cleanupSucceeded = false;
|
||||
}
|
||||
}
|
||||
Set<String> inlineToRestore = new LinkedHashSet<>(inlineRollback);
|
||||
inlineToRestore.addAll(inlineRemovedByThisAttempt);
|
||||
for (String policyName : inlineToRestore) {
|
||||
String prior = originalInlinePolicies.get(policyName);
|
||||
String cleanupDescription = (prior == null ? "remove" : "restore")
|
||||
+ " inline policy " + policyName + " on role " + resolvedRoleName;
|
||||
if (!CfnRollback.attemptIamCleanup(failure, cleanupDescription, () -> {
|
||||
if (prior == null) {
|
||||
iamService.deleteRolePolicy(resolvedRoleName, policyName);
|
||||
} else {
|
||||
iamService.putRolePolicy(resolvedRoleName, policyName, prior);
|
||||
}
|
||||
})) {
|
||||
if (prior != null && !CfnRollback.attemptIamCleanup(failure,
|
||||
"restore inline policy " + policyName + " on role " + resolvedRoleName,
|
||||
() -> iamService.putRolePolicy(resolvedRoleName, policyName, prior))) {
|
||||
cleanupSucceeded = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,6 +99,7 @@ import java.util.stream.Stream;
|
||||
@ApplicationScoped
|
||||
public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
|
||||
private static final int ROLE_INLINE_POLICY_SIZE_LIMIT = 10_240;
|
||||
private static final Logger LOG = Logger.getLogger(IamService.class);
|
||||
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
private static final String TEMPORARY_ACCESS_KEY_PREFIX = "ASIA";
|
||||
@@ -1806,8 +1807,30 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
public void putRolePolicy(String roleName, String policyName, String policyDocument) {
|
||||
IamRole role = getRole(roleName);
|
||||
requireNotServiceLinked(role, roleName);
|
||||
role.getInlinePolicies().put(policyName, policyDocument);
|
||||
roles.put(roleName, role);
|
||||
Map<String, String> inlinePolicies = role.getInlinePolicies();
|
||||
synchronized (inlinePolicies) {
|
||||
long aggregateSize = inlinePolicies.entrySet().stream()
|
||||
.filter(entry -> !entry.getKey().equals(policyName))
|
||||
.mapToLong(entry -> nonWhitespaceLength(entry.getValue()))
|
||||
.sum() + nonWhitespaceLength(policyDocument);
|
||||
if (aggregateSize > ROLE_INLINE_POLICY_SIZE_LIMIT) {
|
||||
throw new AwsException("LimitExceeded",
|
||||
"Maximum policy size of 10240 bytes exceeded for role " + roleName, 409);
|
||||
}
|
||||
inlinePolicies.put(policyName, policyDocument);
|
||||
roles.put(roleName, role);
|
||||
}
|
||||
}
|
||||
|
||||
private static int nonWhitespaceLength(String policyDocument) {
|
||||
int size = 0;
|
||||
for (int i = 0; i < policyDocument.length(); i++) {
|
||||
char character = policyDocument.charAt(i);
|
||||
if (character != ' ' && character != '\t' && character != '\n' && character != '\r') {
|
||||
size++;
|
||||
}
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
public String getRolePolicy(String roleName, String policyName) {
|
||||
|
||||
+38
@@ -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);
|
||||
|
||||
+24
-1
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user