mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(iam): enforce user and group inline policy quotas (#5590)
This commit is contained in:
1 parent
04942063a7
commit
1d8f65d231
16 files changed
+1569
-222
No files matched your search
+128
-74
@@ -5,18 +5,20 @@ import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.IamService.InlinePolicyChange;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* CloudFormation provisioning for {@code AWS::IAM::Policy}, which in AWS is an <em>inline</em>
|
||||
@@ -90,36 +92,44 @@ public class IamPolicyCfnProvisioner implements CfnResourceProvisioner {
|
||||
List<String> roleTargets = new ArrayList<>();
|
||||
List<String> userTargets = new ArrayList<>();
|
||||
List<String> groupTargets = new ArrayList<>();
|
||||
List<InlinePolicyUndo> writtenPolicies = new ArrayList<>();
|
||||
List<InlinePolicyUndo> removedPolicies = new ArrayList<>();
|
||||
try {
|
||||
List<String> desiredRoles = resolveInlineTargets(props, "Roles", engine);
|
||||
List<String> desiredUsers = resolveInlineTargets(props, "Users", engine);
|
||||
List<String> desiredGroups = resolveInlineTargets(props, "Groups", engine);
|
||||
cleanupPendingInlinePolicies(r);
|
||||
putInlinePolicy(props, "Roles", engine, roleTargets,
|
||||
principal -> iamService.putRolePolicy(principal, name, doc));
|
||||
putInlinePolicy(props, "Users", engine, userTargets,
|
||||
principal -> iamService.putUserPolicy(principal, name, doc));
|
||||
putInlinePolicy(props, "Groups", engine, groupTargets,
|
||||
principal -> iamService.putGroupPolicy(principal, name, doc));
|
||||
if (!legacyManagedPolicy && previousPolicyName != null && !previousPolicyName.equals(name)) {
|
||||
removeRenamedInlinePolicies(previousRoleTargets, desiredRoles,
|
||||
policyAccess("Role", previousPolicyName), removedPolicies);
|
||||
removeRenamedInlinePolicies(previousUserTargets, desiredUsers,
|
||||
policyAccess("User", previousPolicyName), removedPolicies);
|
||||
removeRenamedInlinePolicies(previousGroupTargets, desiredGroups,
|
||||
policyAccess("Group", previousPolicyName), removedPolicies);
|
||||
}
|
||||
putInlinePolicy(desiredRoles, roleTargets, doc,
|
||||
policyAccess("Role", name), previousPolicyName != null, writtenPolicies);
|
||||
putInlinePolicy(desiredUsers, userTargets, doc,
|
||||
policyAccess("User", name), previousPolicyName != null, writtenPolicies);
|
||||
putInlinePolicy(desiredGroups, groupTargets, doc,
|
||||
policyAccess("Group", name), previousPolicyName != null, writtenPolicies);
|
||||
|
||||
if (legacyManagedPolicy) {
|
||||
migrateLegacyManagedPolicy(r);
|
||||
} else {
|
||||
deleteRemovedInlinePolicies(previousRoleTargets, roleTargets,
|
||||
previousPolicyName, policyName,
|
||||
principal -> iamService.deleteRolePolicy(principal, previousPolicyName));
|
||||
previousPolicyName, policyAccess("Role", previousPolicyName), removedPolicies);
|
||||
deleteRemovedInlinePolicies(previousUserTargets, userTargets,
|
||||
previousPolicyName, policyName,
|
||||
principal -> iamService.deleteUserPolicy(principal, previousPolicyName));
|
||||
previousPolicyName, policyAccess("User", previousPolicyName), removedPolicies);
|
||||
deleteRemovedInlinePolicies(previousGroupTargets, groupTargets,
|
||||
previousPolicyName, policyName,
|
||||
principal -> iamService.deleteGroupPolicy(principal, previousPolicyName));
|
||||
previousPolicyName, policyAccess("Group", previousPolicyName), removedPolicies);
|
||||
}
|
||||
} catch (RuntimeException failure) {
|
||||
if (previousPolicyName == null) {
|
||||
r.setPhysicalId(policyName);
|
||||
recordInlinePolicyTargets(r, roleTargets, userTargets, groupTargets);
|
||||
} else {
|
||||
rollbackInlinePolicyUpdate(r, failure, previousPolicyName, policyName,
|
||||
previousRoleTargets, previousUserTargets, previousGroupTargets,
|
||||
roleTargets, userTargets, groupTargets);
|
||||
rollbackInlinePolicyUpdate(r, failure, policyName, writtenPolicies, removedPolicies);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
@@ -152,18 +162,70 @@ public class IamPolicyCfnProvisioner implements CfnResourceProvisioner {
|
||||
return node != null && node.isArray() && !node.isEmpty();
|
||||
}
|
||||
|
||||
private void putInlinePolicy(JsonNode props, String propName, CloudFormationTemplateEngine engine,
|
||||
List<String> successfulTargets, Consumer<String> op) {
|
||||
if (props == null || !props.has(propName)) {
|
||||
return;
|
||||
private record InlinePolicyAccess(String kind, String name, BiConsumer<String, String> write,
|
||||
BiFunction<String, String, InlinePolicyChange> update,
|
||||
Function<String, InlinePolicyChange> remove) {}
|
||||
|
||||
private record InlinePolicyUndo(InlinePolicyAccess access, String principal, InlinePolicyChange change) {
|
||||
void restore() {
|
||||
change.rollback().run();
|
||||
}
|
||||
for (JsonNode entry : props.get(propName)) {
|
||||
String name = engine.resolve(entry);
|
||||
if (name != null && !name.isBlank()) {
|
||||
op.accept(name);
|
||||
successfulTargets.add(name);
|
||||
}
|
||||
|
||||
private InlinePolicyAccess policyAccess(String kind, String name) {
|
||||
return switch (kind) {
|
||||
case "Role" -> new InlinePolicyAccess(kind, name,
|
||||
(principal, document) -> iamService.putRolePolicy(principal, name, document),
|
||||
(principal, document) -> iamService.putRolePolicyWithRollback(principal, name, document),
|
||||
principal -> iamService.deleteRolePolicyWithRollback(principal, name));
|
||||
case "User" -> new InlinePolicyAccess(kind, name,
|
||||
(principal, document) -> iamService.putUserPolicy(principal, name, document),
|
||||
(principal, document) -> iamService.putUserPolicyWithRollback(principal, name, document),
|
||||
principal -> iamService.deleteUserPolicyWithRollback(principal, name));
|
||||
case "Group" -> new InlinePolicyAccess(kind, name,
|
||||
(principal, document) -> iamService.putGroupPolicy(principal, name, document),
|
||||
(principal, document) -> iamService.putGroupPolicyWithRollback(principal, name, document),
|
||||
principal -> iamService.deleteGroupPolicyWithRollback(principal, name));
|
||||
default -> throw new IllegalArgumentException(kind);
|
||||
};
|
||||
}
|
||||
|
||||
private List<String> resolveInlineTargets(JsonNode props, String propName, CloudFormationTemplateEngine engine) {
|
||||
List<String> targets = new ArrayList<>();
|
||||
if (props != null && props.has(propName)) {
|
||||
for (JsonNode entry : props.get(propName)) {
|
||||
String name = engine.resolve(entry);
|
||||
if (name != null && !name.isBlank()) {
|
||||
targets.add(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
private void putInlinePolicy(List<String> targets, List<String> successfulTargets,
|
||||
String document, InlinePolicyAccess access,
|
||||
boolean updating, List<InlinePolicyUndo> writtenPolicies) {
|
||||
for (String name : targets) {
|
||||
if (updating) {
|
||||
InlinePolicyChange change = access.update().apply(name, document);
|
||||
writtenPolicies.add(new InlinePolicyUndo(access, name, change));
|
||||
} else {
|
||||
access.write().accept(name, document);
|
||||
}
|
||||
successfulTargets.add(name);
|
||||
}
|
||||
}
|
||||
|
||||
private void removeRenamedInlinePolicies(String previousTargets, List<String> desiredTargets,
|
||||
InlinePolicyAccess access, List<InlinePolicyUndo> removedPolicies) {
|
||||
Set<String> retainedTargets = new HashSet<>(desiredTargets);
|
||||
detachInline(previousTargets, name -> {
|
||||
if (retainedTargets.contains(name)) {
|
||||
InlinePolicyChange change = access.remove().apply(name);
|
||||
removedPolicies.add(new InlinePolicyUndo(access, name, change));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void recordInlinePolicyTargets(StackResource resource, List<String> roleTargets,
|
||||
@@ -178,44 +240,42 @@ public class IamPolicyCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
|
||||
private void rollbackInlinePolicyUpdate(StackResource resource, RuntimeException failure,
|
||||
String previousPolicyName, String currentPolicyName,
|
||||
String previousRoleTargets, String previousUserTargets,
|
||||
String previousGroupTargets, List<String> appliedRoleTargets,
|
||||
List<String> appliedUserTargets, List<String> appliedGroupTargets) {
|
||||
List<String> pendingRoles = rollbackAppliedInlinePolicies(
|
||||
failure, previousRoleTargets, appliedRoleTargets, previousPolicyName, currentPolicyName,
|
||||
principal -> iamService.deleteRolePolicy(principal, currentPolicyName));
|
||||
List<String> pendingUsers = rollbackAppliedInlinePolicies(
|
||||
failure, previousUserTargets, appliedUserTargets, previousPolicyName, currentPolicyName,
|
||||
principal -> iamService.deleteUserPolicy(principal, currentPolicyName));
|
||||
List<String> pendingGroups = rollbackAppliedInlinePolicies(
|
||||
failure, previousGroupTargets, appliedGroupTargets, previousPolicyName, currentPolicyName,
|
||||
principal -> iamService.deleteGroupPolicy(principal, currentPolicyName));
|
||||
String currentPolicyName, List<InlinePolicyUndo> writtenPolicies,
|
||||
List<InlinePolicyUndo> removedPolicies) {
|
||||
List<String> pendingRoles = new ArrayList<>();
|
||||
List<String> pendingUsers = new ArrayList<>();
|
||||
List<String> pendingGroups = new ArrayList<>();
|
||||
// Undo puts first so restored old names do not compete with this attempt's new names for quota.
|
||||
List<InlinePolicyUndo> rollback = new ArrayList<>(writtenPolicies.reversed());
|
||||
rollback.addAll(removedPolicies.reversed());
|
||||
boolean restored = true;
|
||||
for (InlinePolicyUndo undo : rollback) {
|
||||
String description = "restore inline policy " + undo.access().name() + " on " + undo.principal();
|
||||
if (!CfnRollback.attemptIamCleanup(failure, description, undo::restore)) {
|
||||
restored = false;
|
||||
Throwable[] cleanupFailures = failure.getSuppressed();
|
||||
Throwable cleanupFailure = cleanupFailures[cleanupFailures.length - 1];
|
||||
boolean ownershipChanged = cleanupFailure instanceof AwsException aws
|
||||
&& "ConcurrentModification".equals(aws.getErrorCode());
|
||||
if (!ownershipChanged && undo.change().previousDocument() == null
|
||||
&& currentPolicyName.equals(undo.access().name())) {
|
||||
switch (undo.access().kind()) {
|
||||
case "Role" -> pendingRoles.add(undo.principal());
|
||||
case "User" -> pendingUsers.add(undo.principal());
|
||||
case "Group" -> pendingGroups.add(undo.principal());
|
||||
default -> throw new IllegalArgumentException(undo.access().kind());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
recordPendingInlineCleanup(resource, currentPolicyName, pendingRoles, pendingUsers, pendingGroups);
|
||||
resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true");
|
||||
}
|
||||
|
||||
private List<String> rollbackAppliedInlinePolicies(RuntimeException failure, String previousTargets,
|
||||
List<String> appliedTargets, String previousPolicyName,
|
||||
String currentPolicyName, Consumer<String> cleanup) {
|
||||
Set<String> previous = inlineTargetSet(previousTargets);
|
||||
List<String> rollbackTargets = new ArrayList<>();
|
||||
for (String target : new LinkedHashSet<>(appliedTargets)) {
|
||||
if (!previousPolicyName.equals(currentPolicyName) || !previous.contains(target)) {
|
||||
rollbackTargets.add(target);
|
||||
}
|
||||
resource.getAttributes().remove(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR);
|
||||
if (restored) {
|
||||
resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true");
|
||||
} else {
|
||||
resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR,
|
||||
"Could not restore inline policies after failed update: " + failure.getMessage());
|
||||
}
|
||||
Collections.reverse(rollbackTargets);
|
||||
|
||||
List<String> pendingTargets = new ArrayList<>();
|
||||
for (String target : rollbackTargets) {
|
||||
String description = "delete inline policy " + currentPolicyName + " from " + target;
|
||||
if (!CfnRollback.attemptIamCleanup(failure, description, () -> detachInline(target, cleanup))) {
|
||||
pendingTargets.add(target);
|
||||
}
|
||||
}
|
||||
Collections.reverse(pendingTargets);
|
||||
return pendingTargets;
|
||||
}
|
||||
|
||||
private void recordPendingInlineCleanup(StackResource resource, String policyName,
|
||||
@@ -248,27 +308,21 @@ public class IamPolicyCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
|
||||
private void deleteRemovedInlinePolicies(String previousTargets, List<String> currentTargets,
|
||||
String previousPolicyName, String currentPolicyName,
|
||||
Consumer<String> op) {
|
||||
String previousPolicyName,
|
||||
InlinePolicyAccess access, List<InlinePolicyUndo> removedPolicies) {
|
||||
if (previousPolicyName == null) {
|
||||
return;
|
||||
}
|
||||
Set<String> retainedTargets = new HashSet<>(currentTargets);
|
||||
detachInline(previousTargets, name -> {
|
||||
if (!previousPolicyName.equals(currentPolicyName) || !retainedTargets.contains(name)) {
|
||||
op.accept(name);
|
||||
if (!retainedTargets.contains(name)) {
|
||||
InlinePolicyChange change = access.remove().apply(name);
|
||||
removedPolicies.add(new InlinePolicyUndo(access, name, change));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Set<String> inlineTargetSet(String targets) {
|
||||
if (targets == null || targets.isBlank()) {
|
||||
return Set.of();
|
||||
}
|
||||
return new HashSet<>(Arrays.asList(targets.split("\n")));
|
||||
}
|
||||
|
||||
private void detachInline(String targets, Consumer<String> op) {
|
||||
private static void detachInline(String targets, Consumer<String> op) {
|
||||
if (targets == null || targets.isBlank()) {
|
||||
return;
|
||||
}
|
||||
|
||||
+27
-32
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.IamService.InlinePolicyChange;
|
||||
import io.github.hectorvent.floci.services.iam.model.AccessKey;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamUser;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -15,6 +16,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;
|
||||
@@ -42,6 +44,8 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
|
||||
this.iamService = iamService;
|
||||
}
|
||||
|
||||
private record InlinePolicyUndo(String name, InlinePolicyChange change) {}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of("AWS::IAM::User");
|
||||
@@ -130,7 +134,7 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
|
||||
LinkedHashSet<String> attachedByThisAttempt = new LinkedHashSet<>();
|
||||
LinkedHashSet<String> detachedByThisAttempt = new LinkedHashSet<>();
|
||||
LinkedHashSet<String> inlineWrittenByThisAttempt = new LinkedHashSet<>();
|
||||
LinkedHashSet<String> inlineRemovedByThisAttempt = new LinkedHashSet<>();
|
||||
List<InlinePolicyUndo> inlineChanges = new ArrayList<>();
|
||||
boolean tagMutationStarted = false;
|
||||
|
||||
final String pathToRestore = priorPath;
|
||||
@@ -165,6 +169,7 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, String> desiredInlinePolicies = new LinkedHashMap<>();
|
||||
if (props != null && props.has("Policies")) {
|
||||
for (JsonNode policy : props.get("Policies")) {
|
||||
String declaredName = ctx.resolveOptional(policy, "PolicyName");
|
||||
@@ -179,19 +184,23 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
|
||||
"Inline policy '" + policyName + "' on user " + resolvedUserName
|
||||
+ " has no PolicyDocument.", 400);
|
||||
}
|
||||
iamService.putUserPolicy(resolvedUserName, policyName,
|
||||
ctx.engine().resolveJsonAttributeStrict(document));
|
||||
inlineWrittenByThisAttempt.add(policyName);
|
||||
desiredInlinePolicies.put(policyName, ctx.engine().resolveJsonAttributeStrict(document));
|
||||
}
|
||||
}
|
||||
|
||||
for (String stale : previousInlineNames) {
|
||||
if (!inlineWrittenByThisAttempt.contains(stale)
|
||||
&& originalInlinePolicies.containsKey(stale)) {
|
||||
iamService.deleteUserPolicy(resolvedUserName, stale);
|
||||
inlineRemovedByThisAttempt.add(stale);
|
||||
if (originalInlinePolicies.containsKey(stale)
|
||||
&& !originalInlinePolicies.get(stale).equals(desiredInlinePolicies.get(stale))) {
|
||||
inlineChanges.add(new InlinePolicyUndo(stale,
|
||||
iamService.deleteUserPolicyWithRollback(resolvedUserName, stale)));
|
||||
}
|
||||
}
|
||||
// Release replaced documents before writing, including policies that retain their names.
|
||||
for (Map.Entry<String, String> policy : desiredInlinePolicies.entrySet()) {
|
||||
inlineChanges.add(new InlinePolicyUndo(policy.getKey(), iamService.putUserPolicyWithRollback(
|
||||
resolvedUserName, policy.getKey(), policy.getValue())));
|
||||
inlineWrittenByThisAttempt.add(policy.getKey());
|
||||
}
|
||||
for (String stale : previousManagedArns) {
|
||||
if (!managedPolicyArns.contains(stale) && originalPolicyArns.contains(stale)) {
|
||||
iamService.detachUserPolicy(resolvedUserName, stale);
|
||||
@@ -240,17 +249,6 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
|
||||
cleanupSucceeded = false;
|
||||
}
|
||||
}
|
||||
for (String policyName : inlineRemovedByThisAttempt) {
|
||||
String prior = originalInlinePolicies.get(policyName);
|
||||
if (prior == null) {
|
||||
continue;
|
||||
}
|
||||
if (!CfnRollback.attemptIamCleanup(failure,
|
||||
"restore inline policy " + policyName + " on user " + resolvedUserName,
|
||||
() -> iamService.putUserPolicy(resolvedUserName, policyName, prior))) {
|
||||
cleanupSucceeded = false;
|
||||
}
|
||||
}
|
||||
for (String policyArn : detachedByThisAttempt) {
|
||||
if (!CfnRollback.attemptIamCleanup(failure,
|
||||
"reattach policy " + policyArn + " to user " + resolvedUserName,
|
||||
@@ -259,19 +257,11 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
}
|
||||
|
||||
List<String> inlineRollback = new ArrayList<>(inlineWrittenByThisAttempt);
|
||||
Collections.reverse(inlineRollback);
|
||||
for (String policyName : inlineRollback) {
|
||||
String prior = originalInlinePolicies.get(policyName);
|
||||
String cleanupDescription = (prior == null ? "remove" : "restore")
|
||||
+ " inline policy " + policyName + " on user " + resolvedUserName;
|
||||
if (!CfnRollback.attemptIamCleanup(failure, cleanupDescription, () -> {
|
||||
if (prior == null) {
|
||||
iamService.deleteUserPolicy(resolvedUserName, policyName);
|
||||
} else {
|
||||
iamService.putUserPolicy(resolvedUserName, policyName, prior);
|
||||
}
|
||||
})) {
|
||||
for (InlinePolicyUndo undo : inlineChanges.reversed()) {
|
||||
String operation = undo.change().previousDocument() == null ? "remove" : "restore";
|
||||
if (!CfnRollback.attemptIamCleanup(failure,
|
||||
operation + " inline policy " + undo.name() + " on user " + resolvedUserName,
|
||||
undo.change().rollback())) {
|
||||
cleanupSucceeded = false;
|
||||
}
|
||||
}
|
||||
@@ -325,6 +315,11 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
|
||||
r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
|
||||
}
|
||||
}
|
||||
if (!createdUser && !cleanupSucceeded) {
|
||||
r.getAttributes().remove(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR);
|
||||
r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR,
|
||||
"Could not restore user after failed update: " + failure.getMessage());
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
|
||||
|
||||
@@ -104,6 +104,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
public static final String FEDERATION_TOKEN_SESSION_MESSAGE =
|
||||
"Cannot call GetFederationToken with session credentials";
|
||||
|
||||
private static final int USER_INLINE_POLICY_SIZE_LIMIT = 2_048;
|
||||
private static final int GROUP_INLINE_POLICY_SIZE_LIMIT = 5_120;
|
||||
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";
|
||||
@@ -771,61 +773,63 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
|
||||
public void deleteUser(String userName) {
|
||||
IamUser user = getUser(userName);
|
||||
if (!user.getAttachedPolicyArns().isEmpty()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must detach all policies first.", 409);
|
||||
}
|
||||
if (!user.getGroupNames().isEmpty()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must remove from all groups first.", 409);
|
||||
}
|
||||
if (loginProfiles.get(userName).isPresent()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must delete login profile first.", 409);
|
||||
}
|
||||
if (!user.getInlinePolicies().isEmpty()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must delete policies first.", 409);
|
||||
}
|
||||
if (!userAccessKeys(userName).isEmpty()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must delete access keys first.", 409);
|
||||
}
|
||||
// Both locks are held across the delete rather than just the checks: UploadSigningCertificate
|
||||
// UploadSigningCertificate and EnableMFADevice confirm the user under their own lock, so
|
||||
// none of them can interleave into a credential owned by a deleted user. Taken in this
|
||||
// order here and in UpdateUser, and nowhere else in more than one, so it cannot deadlock.
|
||||
synchronized (serviceCredentialLock) {
|
||||
// AWS lists these among the items to remove first, under their CodeCommit
|
||||
// name: "Git credentials (DeleteServiceSpecificCredential)". Unlike the
|
||||
// cases above it has no message of its own: AWS falls back to the generic
|
||||
// referenced-objects wording here.
|
||||
if (!userServiceCredentials(userName).isEmpty()) {
|
||||
synchronized (resourceNameLock) {
|
||||
IamUser user = getUser(userName);
|
||||
if (!user.getAttachedPolicyArns().isEmpty()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must remove referenced objects first.", 409);
|
||||
"Cannot delete entity, must detach all policies first.", 409);
|
||||
}
|
||||
synchronized (sshPublicKeyLock) {
|
||||
if (!userSshPublicKeys(userName).isEmpty()) {
|
||||
if (!user.getGroupNames().isEmpty()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must remove from all groups first.", 409);
|
||||
}
|
||||
if (loginProfiles.get(userName).isPresent()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must delete login profile first.", 409);
|
||||
}
|
||||
if (!user.getInlinePolicies().isEmpty()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must delete policies first.", 409);
|
||||
}
|
||||
if (!userAccessKeys(userName).isEmpty()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must delete access keys first.", 409);
|
||||
}
|
||||
// Both locks are held across the delete rather than just the checks: UploadSigningCertificate
|
||||
// UploadSigningCertificate and EnableMFADevice confirm the user under their own lock, so
|
||||
// none of them can interleave into a credential owned by a deleted user. Taken in this
|
||||
// order here and in UpdateUser, and nowhere else in more than one, so it cannot deadlock.
|
||||
synchronized (serviceCredentialLock) {
|
||||
// AWS lists these among the items to remove first, under their CodeCommit
|
||||
// name: "Git credentials (DeleteServiceSpecificCredential)". Unlike the
|
||||
// cases above it has no message of its own: AWS falls back to the generic
|
||||
// referenced-objects wording here.
|
||||
if (!userServiceCredentials(userName).isEmpty()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must delete SSH public keys first.", 409);
|
||||
"Cannot delete entity, must remove referenced objects first.", 409);
|
||||
}
|
||||
synchronized (signingCertificateLock) {
|
||||
if (!userSigningCertificates(userName).isEmpty()) {
|
||||
synchronized (sshPublicKeyLock) {
|
||||
if (!userSshPublicKeys(userName).isEmpty()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must delete signing certificates first.", 409);
|
||||
"Cannot delete entity, must delete SSH public keys first.", 409);
|
||||
}
|
||||
synchronized (mfaDeviceLock) {
|
||||
if (!mfaDevicesForUser(userName).isEmpty()) {
|
||||
synchronized (signingCertificateLock) {
|
||||
if (!userSigningCertificates(userName).isEmpty()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must deactivate MFA device first.", 409);
|
||||
"Cannot delete entity, must delete signing certificates first.", 409);
|
||||
}
|
||||
synchronized (mfaDeviceLock) {
|
||||
if (!mfaDevicesForUser(userName).isEmpty()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must deactivate MFA device first.", 409);
|
||||
}
|
||||
users.delete(userName);
|
||||
}
|
||||
users.delete(userName);
|
||||
}
|
||||
}
|
||||
}
|
||||
LOG.infov("Deleted IAM user: {0}", userName);
|
||||
}
|
||||
LOG.infov("Deleted IAM user: {0}", userName);
|
||||
}
|
||||
|
||||
public List<IamUser> listUsers(String pathPrefix) {
|
||||
@@ -1029,17 +1033,19 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
|
||||
public void deleteGroup(String groupName) {
|
||||
IamGroup group = getGroup(groupName);
|
||||
if (!group.getAttachedPolicyArns().isEmpty() || !group.getInlinePolicies().isEmpty()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must detach all policies first.", 409);
|
||||
synchronized (resourceNameLock) {
|
||||
IamGroup group = getGroup(groupName);
|
||||
if (!group.getAttachedPolicyArns().isEmpty() || !group.getInlinePolicies().isEmpty()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must detach all policies first.", 409);
|
||||
}
|
||||
if (!group.getUserNames().isEmpty()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must remove all users from group first.", 409);
|
||||
}
|
||||
groups.delete(groupName);
|
||||
LOG.infov("Deleted IAM group: {0}", groupName);
|
||||
}
|
||||
if (!group.getUserNames().isEmpty()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must remove all users from group first.", 409);
|
||||
}
|
||||
groups.delete(groupName);
|
||||
LOG.infov("Deleted IAM group: {0}", groupName);
|
||||
}
|
||||
|
||||
public List<IamGroup> listGroups(String pathPrefix) {
|
||||
@@ -1211,15 +1217,17 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
|
||||
public void deleteRole(String roleName) {
|
||||
validateRoleName(roleName);
|
||||
IamRole role = getRole(roleName);
|
||||
requireNotServiceLinked(role, roleName);
|
||||
if (!role.getAttachedPolicyArns().isEmpty() || !role.getInlinePolicies().isEmpty()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must detach all policies first.", 409);
|
||||
synchronized (resourceNameLock) {
|
||||
validateRoleName(roleName);
|
||||
IamRole role = getRole(roleName);
|
||||
requireNotServiceLinked(role, roleName);
|
||||
if (!role.getAttachedPolicyArns().isEmpty() || !role.getInlinePolicies().isEmpty()) {
|
||||
throw new AwsException("DeleteConflict",
|
||||
"Cannot delete entity, must detach all policies first.", 409);
|
||||
}
|
||||
roles.delete(roleName);
|
||||
LOG.infov("Deleted IAM role: {0}", roleName);
|
||||
}
|
||||
roles.delete(roleName);
|
||||
LOG.infov("Deleted IAM role: {0}", roleName);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1631,9 +1639,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
summary.put("AttachedPoliciesPerUserQuota", 10L);
|
||||
summary.put("AttachedPoliciesPerGroupQuota", 10L);
|
||||
summary.put("AttachedPoliciesPerRoleQuota", 20L);
|
||||
summary.put("GroupPolicySizeQuota", 5120L);
|
||||
summary.put("UserPolicySizeQuota", 2048L);
|
||||
summary.put("RolePolicySizeQuota", 10240L);
|
||||
summary.put("GroupPolicySizeQuota", (long) GROUP_INLINE_POLICY_SIZE_LIMIT);
|
||||
summary.put("UserPolicySizeQuota", (long) USER_INLINE_POLICY_SIZE_LIMIT);
|
||||
summary.put("RolePolicySizeQuota", (long) ROLE_INLINE_POLICY_SIZE_LIMIT);
|
||||
summary.put("AccessKeysPerUserQuota", 2L);
|
||||
summary.put("SigningCertificatesPerUserQuota", 2L);
|
||||
summary.put("ServerCertificates", (long) serverCertificates.scan(k -> true).size());
|
||||
@@ -1884,9 +1892,16 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
// =========================================================================
|
||||
|
||||
public void putUserPolicy(String userName, String policyName, String policyDocument) {
|
||||
IamUser user = getUser(userName);
|
||||
user.getInlinePolicies().put(policyName, policyDocument);
|
||||
users.put(userName, user);
|
||||
synchronized (resourceNameLock) {
|
||||
IamUser user = getUser(userName);
|
||||
Map<String, String> inlinePolicies = user.getInlinePolicies();
|
||||
synchronized (inlinePolicies) {
|
||||
checkInlinePolicyQuota(inlinePolicies, policyName, policyDocument,
|
||||
USER_INLINE_POLICY_SIZE_LIMIT, "user " + userName);
|
||||
inlinePolicies.put(policyName, policyDocument);
|
||||
users.put(userName, user);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String getUserPolicy(String userName, String policyName) {
|
||||
@@ -1900,12 +1915,14 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
|
||||
public void deleteUserPolicy(String userName, String policyName) {
|
||||
IamUser user = getUser(userName);
|
||||
if (user.getInlinePolicies().remove(policyName) == null) {
|
||||
throw new AwsException("NoSuchEntity",
|
||||
"Policy " + policyName + " not found for user " + userName + ".", 404);
|
||||
synchronized (resourceNameLock) {
|
||||
IamUser user = getUser(userName);
|
||||
if (user.getInlinePolicies().remove(policyName) == null) {
|
||||
throw new AwsException("NoSuchEntity",
|
||||
"Policy " + policyName + " not found for user " + userName + ".", 404);
|
||||
}
|
||||
users.put(userName, user);
|
||||
}
|
||||
users.put(userName, user);
|
||||
}
|
||||
|
||||
public List<String> listUserPolicies(String userName) {
|
||||
@@ -1917,9 +1934,16 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
// =========================================================================
|
||||
|
||||
public void putGroupPolicy(String groupName, String policyName, String policyDocument) {
|
||||
IamGroup group = getGroup(groupName);
|
||||
group.getInlinePolicies().put(policyName, policyDocument);
|
||||
groups.put(groupName, group);
|
||||
synchronized (resourceNameLock) {
|
||||
IamGroup group = getGroup(groupName);
|
||||
Map<String, String> inlinePolicies = group.getInlinePolicies();
|
||||
synchronized (inlinePolicies) {
|
||||
checkInlinePolicyQuota(inlinePolicies, policyName, policyDocument,
|
||||
GROUP_INLINE_POLICY_SIZE_LIMIT, "group " + groupName);
|
||||
inlinePolicies.put(policyName, policyDocument);
|
||||
groups.put(groupName, group);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String getGroupPolicy(String groupName, String policyName) {
|
||||
@@ -1933,12 +1957,14 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
|
||||
public void deleteGroupPolicy(String groupName, String policyName) {
|
||||
IamGroup group = getGroup(groupName);
|
||||
if (group.getInlinePolicies().remove(policyName) == null) {
|
||||
throw new AwsException("NoSuchEntity",
|
||||
"Policy " + policyName + " not found for group " + groupName + ".", 404);
|
||||
synchronized (resourceNameLock) {
|
||||
IamGroup group = getGroup(groupName);
|
||||
if (group.getInlinePolicies().remove(policyName) == null) {
|
||||
throw new AwsException("NoSuchEntity",
|
||||
"Policy " + policyName + " not found for group " + groupName + ".", 404);
|
||||
}
|
||||
groups.put(groupName, group);
|
||||
}
|
||||
groups.put(groupName, group);
|
||||
}
|
||||
|
||||
public List<String> listGroupPolicies(String groupName) {
|
||||
@@ -1950,24 +1976,141 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
// =========================================================================
|
||||
|
||||
public void putRolePolicy(String roleName, String policyName, String policyDocument) {
|
||||
validateRoleName(roleName);
|
||||
IamRole role = getRole(roleName);
|
||||
requireNotServiceLinked(role, roleName);
|
||||
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);
|
||||
synchronized (resourceNameLock) {
|
||||
validateRoleName(roleName);
|
||||
IamRole role = getRole(roleName);
|
||||
requireNotServiceLinked(role, roleName);
|
||||
Map<String, String> inlinePolicies = role.getInlinePolicies();
|
||||
synchronized (inlinePolicies) {
|
||||
checkInlinePolicyQuota(inlinePolicies, policyName, policyDocument,
|
||||
ROLE_INLINE_POLICY_SIZE_LIMIT, "role " + roleName);
|
||||
inlinePolicies.put(policyName, policyDocument);
|
||||
roles.put(roleName, role);
|
||||
}
|
||||
inlinePolicies.put(policyName, policyDocument);
|
||||
roles.put(roleName, role);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* CloudFormation compensation captures the stored document with the write. The returned
|
||||
* operation can restore that exact historical value, including policies saved before quotas
|
||||
* were enforced; it cannot admit a caller-supplied oversized replacement.
|
||||
*/
|
||||
public InlinePolicyChange putUserPolicyWithRollback(String userName, String policyName, String document) {
|
||||
return changeInlinePolicy(users, userName, policyName, () -> getUser(userName),
|
||||
IamUser::getUserId,
|
||||
IamUser::getInlinePolicies, () -> putUserPolicy(userName, policyName, document),
|
||||
document, USER_INLINE_POLICY_SIZE_LIMIT);
|
||||
}
|
||||
|
||||
public InlinePolicyChange deleteUserPolicyWithRollback(String userName, String policyName) {
|
||||
return changeInlinePolicy(users, userName, policyName, () -> getUser(userName),
|
||||
IamUser::getUserId,
|
||||
IamUser::getInlinePolicies, () -> deleteUserPolicy(userName, policyName),
|
||||
null, USER_INLINE_POLICY_SIZE_LIMIT);
|
||||
}
|
||||
|
||||
public InlinePolicyChange putGroupPolicyWithRollback(String groupName, String policyName, String document) {
|
||||
return changeInlinePolicy(groups, groupName, policyName, () -> getGroup(groupName),
|
||||
IamGroup::getGroupId,
|
||||
IamGroup::getInlinePolicies, () -> putGroupPolicy(groupName, policyName, document),
|
||||
document, GROUP_INLINE_POLICY_SIZE_LIMIT);
|
||||
}
|
||||
|
||||
public InlinePolicyChange deleteGroupPolicyWithRollback(String groupName, String policyName) {
|
||||
return changeInlinePolicy(groups, groupName, policyName, () -> getGroup(groupName),
|
||||
IamGroup::getGroupId,
|
||||
IamGroup::getInlinePolicies, () -> deleteGroupPolicy(groupName, policyName),
|
||||
null, GROUP_INLINE_POLICY_SIZE_LIMIT);
|
||||
}
|
||||
|
||||
public InlinePolicyChange putRolePolicyWithRollback(String roleName, String policyName, String document) {
|
||||
return changeInlinePolicy(roles, roleName, policyName, () -> getValidatedRole(roleName),
|
||||
IamRole::getRoleId,
|
||||
IamRole::getInlinePolicies, () -> putRolePolicy(roleName, policyName, document),
|
||||
document, ROLE_INLINE_POLICY_SIZE_LIMIT);
|
||||
}
|
||||
|
||||
public InlinePolicyChange deleteRolePolicyWithRollback(String roleName, String policyName) {
|
||||
return changeInlinePolicy(roles, roleName, policyName, () -> getValidatedRole(roleName),
|
||||
IamRole::getRoleId,
|
||||
IamRole::getInlinePolicies, () -> deleteRolePolicy(roleName, policyName),
|
||||
null, ROLE_INLINE_POLICY_SIZE_LIMIT);
|
||||
}
|
||||
|
||||
private <T> InlinePolicyChange changeInlinePolicy(StorageBackend<String, T> store, String principal,
|
||||
String policyName, Supplier<T> lookup, Function<T, String> identity,
|
||||
Function<T, Map<String, String>> policies,
|
||||
Runnable change, String expectedDocument, int limit) {
|
||||
synchronized (resourceNameLock) {
|
||||
T original = lookup.get();
|
||||
String account = regionResolver.getAccountId();
|
||||
String principalId = identity.apply(original);
|
||||
Map<String, String> inlinePolicies = policies.apply(original);
|
||||
synchronized (inlinePolicies) {
|
||||
String previousDocument = inlinePolicies.get(policyName);
|
||||
Map<String, String> previousSiblings = new LinkedHashMap<>(inlinePolicies);
|
||||
previousSiblings.remove(policyName);
|
||||
change.run();
|
||||
return new InlinePolicyChange(previousDocument, () -> {
|
||||
synchronized (resourceNameLock) {
|
||||
if (!account.equals(regionResolver.getAccountId())) {
|
||||
throw inlinePolicyRollbackConflict(principal, policyName);
|
||||
}
|
||||
T current = store.get(principal).orElseThrow(() ->
|
||||
inlinePolicyRollbackConflict(principal, policyName));
|
||||
if (!Objects.equals(principalId, identity.apply(current))) {
|
||||
throw inlinePolicyRollbackConflict(principal, policyName);
|
||||
}
|
||||
Map<String, String> currentPolicies = policies.apply(current);
|
||||
synchronized (currentPolicies) {
|
||||
if (!Objects.equals(expectedDocument, currentPolicies.get(policyName))) {
|
||||
throw inlinePolicyRollbackConflict(principal, policyName);
|
||||
}
|
||||
if (previousDocument != null
|
||||
&& inlinePolicySize(currentPolicies, policyName, previousDocument) > limit) {
|
||||
Map<String, String> currentSiblings = new LinkedHashMap<>(currentPolicies);
|
||||
currentSiblings.remove(policyName);
|
||||
if (!previousSiblings.equals(currentSiblings)) {
|
||||
throw inlinePolicyRollbackConflict(principal, policyName);
|
||||
}
|
||||
}
|
||||
if (previousDocument == null) {
|
||||
currentPolicies.remove(policyName);
|
||||
} else {
|
||||
currentPolicies.put(policyName, previousDocument);
|
||||
}
|
||||
store.put(principal, current);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public record InlinePolicyChange(String previousDocument, Runnable rollback) {}
|
||||
|
||||
private static AwsException inlinePolicyRollbackConflict(String principal, String policyName) {
|
||||
return new AwsException("ConcurrentModification",
|
||||
"Cannot restore inline policy " + policyName + " on " + principal
|
||||
+ " because its principal or document changed after the update.", 409);
|
||||
}
|
||||
|
||||
private static void checkInlinePolicyQuota(Map<String, String> inlinePolicies, String policyName,
|
||||
String policyDocument, int limit, String principal) {
|
||||
long aggregateSize = inlinePolicySize(inlinePolicies, policyName, policyDocument);
|
||||
if (aggregateSize > limit) {
|
||||
throw new AwsException("LimitExceeded",
|
||||
"Maximum policy size of " + limit + " bytes exceeded for " + principal, 409);
|
||||
}
|
||||
}
|
||||
|
||||
private static long inlinePolicySize(Map<String, String> policies, String name, String document) {
|
||||
return policies.entrySet().stream()
|
||||
.filter(entry -> !entry.getKey().equals(name))
|
||||
.mapToLong(entry -> nonWhitespaceLength(entry.getValue()))
|
||||
.sum() + nonWhitespaceLength(document);
|
||||
}
|
||||
|
||||
private static int nonWhitespaceLength(String policyDocument) {
|
||||
int size = 0;
|
||||
for (int i = 0; i < policyDocument.length(); i++) {
|
||||
@@ -1991,14 +2134,16 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
|
||||
public void deleteRolePolicy(String roleName, String policyName) {
|
||||
validateRoleName(roleName);
|
||||
IamRole role = getRole(roleName);
|
||||
requireNotServiceLinked(role, roleName);
|
||||
if (role.getInlinePolicies().remove(policyName) == null) {
|
||||
throw new AwsException("NoSuchEntity",
|
||||
"Policy " + policyName + " not found for role " + roleName + ".", 404);
|
||||
synchronized (resourceNameLock) {
|
||||
validateRoleName(roleName);
|
||||
IamRole role = getRole(roleName);
|
||||
requireNotServiceLinked(role, roleName);
|
||||
if (role.getInlinePolicies().remove(policyName) == null) {
|
||||
throw new AwsException("NoSuchEntity",
|
||||
"Policy " + policyName + " not found for role " + roleName + ".", 404);
|
||||
}
|
||||
roles.put(roleName, role);
|
||||
}
|
||||
roles.put(roleName, role);
|
||||
}
|
||||
|
||||
public List<String> listRolePolicies(String roleName) {
|
||||
|
||||
Reference in new issue
Block a user