diff --git a/docs/services/iam.md b/docs/services/iam.md index 885c7e2be1..c16cf9e2f4 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -694,14 +694,53 @@ roles-per-instance-profile quota by any name, and this package used to answer pr Removing a role the profile does not hold is `NoSuchEntity` 404 with `Role in Instance Profile cannot be found.`, where this package removed nothing and answered -200. A role that was deleted while the profile still lists it is a different case and is still -removable, which is what the profile's own list decides. +200. A profile that lists a role which is no longer there is a different case and is still +removable, which is what the profile's own list decides; nothing served reaches that state any +more, since the role cannot be deleted while a profile holds it. The two CloudFormation paths that detach a role read the profile's list and then remove what it named, so a pairing some other caller detaches in between is tolerated there rather than failing a stack delete or an update part way; a profile that has itself gone still ends the delete where it always did. +### What a blocked delete names + +A delete that a dependency blocks is `DeleteConflict` 409, and the sentence it carries names the +one dependency the caller has to clear. The four below are AWS's own, recorded against a real +account across capture runs between 2026-10-25 and 2026-11-16, and each is entirely fixed text: +no entity name, no count, nothing taken from the request. The wording is the contract rather than +a description, because a cleanup loop reads it to choose what to do next. + +| What is still there | What the delete answers | +| --- | --- | +| The role is held by an instance profile | `Cannot delete entity, must remove roles from instance profile first.` | +| The instance profile still holds a role | `Cannot delete entity, must remove roles from instance profile first.` | +| A managed policy is attached | `Cannot delete entity, must detach all policies first.` | +| An inline policy is embedded | `Cannot delete entity, must delete policies first.` | + +The last two are a selection rather than one sentence for both: a managed policy is detached and an +inline one is deleted, so the remedy named is the one that clears what is actually there. That +selection is recorded on the role, the group and the user alike. + +`DeleteRole` reads the three in the order of the table, and the first step of it is recorded too: a +role both held by an instance profile and carrying attached policies is refused for the profile, +which is the answer a cleanup loop needs, since detaching the policy changes nothing while the +pairing is there. Attached ahead of inline is the order `DeleteUser` already answered; which of +those two AWS names first for an entity carrying both is not recorded, so the role and the group +follow the user rather than differ from it. + +This package used to read a role's attached and inline policies together and answer the detach +sentence for either, conflate them the same way on a group, word the instance profile's own +refusal itself, and let a role be deleted while a profile still held it. That last one is a +behavior change for a caller that deleted a role out from under a profile: the profile has to let +go of it first, and the refusal says so. Nothing takes a role out of a profile on the caller's +behalf, on AWS or here. That holds for the two callers that delete a role of their own, the +CloudFormation role provisioner and the Identity Center permission-set cleanup: each asks about the +profile before it clears the policies it owns, so a role it turns out it cannot delete keeps what it +had rather than being emptied by a delete that could not finish, and the refusal reaches the caller. +A stack that owns both resources deletes the profile before the role, since dependents go before +what they depend on. + ### Access Keys | Action | Description | diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisioner.java index 48313f8743..16d7ab3a92 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisioner.java @@ -418,6 +418,10 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { LOG.debugv("IAM role already gone, treating as deleted: {0}", physicalId); return; } + // Asked before anything is cleared: the delete can be refused for an instance profile + // this stack does not own, and nothing takes a role out of one on the caller's behalf, so + // detaching first would leave a role that is still there and no longer has its policies. + iamService.requireNotHeldByAnInstanceProfile(physicalId); for (String policyArn : new ArrayList<>(role.getAttachedPolicyArns())) { iamService.detachRolePolicy(physicalId, policyArn); } diff --git a/src/main/java/io/floci/aws/services/iam/IamService.java b/src/main/java/io/floci/aws/services/iam/IamService.java index 94c25a0786..4e7947f72c 100644 --- a/src/main/java/io/floci/aws/services/iam/IamService.java +++ b/src/main/java/io/floci/aws/services/iam/IamService.java @@ -77,6 +77,7 @@ import java.util.Arrays; import java.util.Base64; import java.util.Collection; import java.util.Comparator; +import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -380,6 +381,19 @@ public class IamService implements SessionAccountLookup, ResourceProvider { private static final String CREDENTIAL_REPORT_KEY = "credential-report"; /** AWS generates a fresh report only if the most recent one is older than this. */ private static final Duration CREDENTIAL_REPORT_MAX_AGE = Duration.ofHours(4); + /** + * The sentences AWS answers a blocked delete with, each of them entirely fixed text: no + * entity name, no count, nothing taken from the request. A cleanup routine reads the sentence + * to choose its next step (detach a managed policy, delete an inline one, or remove a role + * from its instance profile), so the wording is what names the dependency; one that describes + * the blocker instead sends the caller after the wrong remedy. + */ + private static final String MUST_DETACH_POLICIES_FIRST = + "Cannot delete entity, must detach all policies first."; + private static final String MUST_DELETE_POLICIES_FIRST = + "Cannot delete entity, must delete policies first."; + private static final String MUST_REMOVE_PROFILE_ROLES_FIRST = + "Cannot delete entity, must remove roles from instance profile first."; public static final String FEATURE_ROOT_CREDENTIALS = "RootCredentialsManagement"; public static final String FEATURE_ROOT_SESSIONS = "RootSessions"; @@ -494,6 +508,16 @@ public class IamService implements SessionAccountLookup, ResourceProvider { // Undo handles retain their ownership keys; completed attempts leave no permanent history. // Both keys and values are weak because each owner itself holds its canonical key. private final Map> inlinePolicyOwners = new WeakHashMap<>(); + /** + * Which instance profiles hold each role, by storage scope then role name: the reverse of the + * list each profile carries, so a role delete asks a map instead of reading every profile in + * the account. The profiles stay the record and this is only an index into them, kept true by + * being written in the same two places a pairing is, both under {@code resourceNameLock}, + * which is also the only lock under which it may be read. A scope is filled from storage the + * first time it is asked about, so profiles that were already there, from a restart or a + * store this process did not write, are in it before the first answer. + */ + private final Map>> profilesByRole = new HashMap<>(); /** * Guards every check-then-write on a login profile. ChangePassword is the reason it has to * exist: it reads the profile to compare the old password, then writes the new one, so two @@ -1015,8 +1039,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { synchronized (resourceNameLock) { IamUser user = getUser(userName); if (!user.getAttachedPolicyArns().isEmpty()) { - throw new AwsException("DeleteConflict", - "Cannot delete entity, must detach all policies first.", 409); + throw new AwsException("DeleteConflict", MUST_DETACH_POLICIES_FIRST, 409); } if (!user.getGroupNames().isEmpty()) { throw new AwsException("DeleteConflict", @@ -1027,8 +1050,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { "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); + throw new AwsException("DeleteConflict", MUST_DELETE_POLICIES_FIRST, 409); } // The credential locks are held across the delete rather than just the checks: // CreateAccessKey, UploadSigningCertificate and EnableMFADevice each confirm the user @@ -1284,9 +1306,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider { public void deleteGroup(String groupName) { 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.getAttachedPolicyArns().isEmpty()) { + throw new AwsException("DeleteConflict", MUST_DETACH_POLICIES_FIRST, 409); + } + if (!group.getInlinePolicies().isEmpty()) { + throw new AwsException("DeleteConflict", MUST_DELETE_POLICIES_FIRST, 409); } if (!group.getUserNames().isEmpty()) { throw new AwsException("DeleteConflict", @@ -1603,22 +1627,111 @@ public class IamService implements SessionAccountLookup, ResourceProvider { deleteRole(roleName, null); } - /** A service cleanup must not delete a different role that has since taken the name. */ + /** + * A service cleanup must not delete a different role that has since taken the name. + * + *

One dependency is named at a time, and which one comes first is part of what AWS was + * recorded answering: a role both held by an instance profile and carrying attached policies + * is refused for the profile. Attached policies ahead of inline ones is the order + * {@link #deleteUser} already answers; which of those two AWS reports first is not recorded. + */ public void deleteRole(String roleName, String expectedRoleId) { synchronized (resourceNameLock) { validateRoleName(roleName); IamRole role = getRole(roleName); requireSameRole(role, roleName, expectedRoleId); requireNotServiceLinked(role, roleName); - if (!role.getAttachedPolicyArns().isEmpty() || !role.getInlinePolicies().isEmpty()) { - throw new AwsException("DeleteConflict", - "Cannot delete entity, must detach all policies first.", 409); + if (heldByAnInstanceProfile(roleName)) { + throw new AwsException("DeleteConflict", MUST_REMOVE_PROFILE_ROLES_FIRST, 409); + } + if (!role.getAttachedPolicyArns().isEmpty()) { + throw new AwsException("DeleteConflict", MUST_DETACH_POLICIES_FIRST, 409); + } + if (!role.getInlinePolicies().isEmpty()) { + throw new AwsException("DeleteConflict", MUST_DELETE_POLICIES_FIRST, 409); } roles.delete(roleName); LOG.infov("Deleted IAM role: {0}", roleName); } } + /** + * Whether any instance profile still holds the role. The role itself is not re-read, since + * the caller resolved it already and a delete must not answer that a role it just found is + * missing; the membership read takes the profile's own monitor, the one the pairing writes + * hold. It is reached under {@code resourceNameLock}, which the attach path now takes outside + * that monitor, so no pairing can land between this answer and the delete that asked for it. + */ + /** + * Refuses up front what {@link #deleteRole} refuses for an instance profile. A caller that + * clears a role's own policies before deleting it asks first: otherwise a role held by a + * profile it does not own is stripped of its permissions and then cannot be deleted, which + * leaves it live and weaker than it was. The pairing can still be made after this answers, + * and such a caller is no worse off then than it was before the delete checked at all. + */ + public void requireNotHeldByAnInstanceProfile(String roleName) { + synchronized (resourceNameLock) { + if (heldByAnInstanceProfile(roleName)) { + throw new AwsException("DeleteConflict", MUST_REMOVE_PROFILE_ROLES_FIRST, 409); + } + } + } + + private boolean heldByAnInstanceProfile(String roleName) { + return !profilesHolding(roleName).isEmpty(); + } + + /** The profile names holding the role, in this request's storage scope. */ + private Set profilesHolding(String roleName) { + return pairingIndex().getOrDefault(roleName, Set.of()); + } + + /** + * The pairing index for the scope this request reads profiles in, filled from those profiles + * the first time the scope comes up. Callers hold {@code resourceNameLock}: the maps are + * plain ones, and what they hold has to agree with a storage write taken under that lock. + */ + private Map> pairingIndex() { + return profilesByRole.computeIfAbsent(instanceProfileScope(), scope -> { + Map> index = new HashMap<>(); + for (InstanceProfile profile : instanceProfiles.scan(k -> true)) { + List roleNames = profile.getRoleNames(); + synchronized (roleNames) { + for (String roleName : roleNames) { + index.computeIfAbsent(roleName, name -> new HashSet<>()) + .add(profile.getInstanceProfileName()); + } + } + } + return index; + }); + } + + /** + * The account profiles are read in, or the empty string outside account-aware storage. The + * index is scoped exactly as {@code instanceProfiles} is, so one account's pairings are never + * read as another's. + */ + private String instanceProfileScope() { + if (instanceProfiles instanceof AccountAwareStorageBackend aware) { + String accountId = aware.accountId(); + return accountId == null ? "" : accountId; + } + return ""; + } + + private void indexPairing(String instanceProfileName, String roleName) { + pairingIndex().computeIfAbsent(roleName, name -> new HashSet<>()).add(instanceProfileName); + } + + private void unindexPairing(String instanceProfileName, String roleName) { + Map> index = pairingIndex(); + Set holding = index.get(roleName); + if (holding != null && holding.remove(instanceProfileName) && holding.isEmpty()) { + index.remove(roleName); + } + } + /** * The linked service — not the caller and not the principal string — chooses the role-name * prefix, so {@code lex.amazonaws.com} yields {@code AWSServiceRoleForLexBots} and the real name @@ -2956,12 +3069,18 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } public void deleteInstanceProfile(String instanceProfileName) { - InstanceProfile profile = getInstanceProfile(instanceProfileName); - if (!profile.getRoleNames().isEmpty()) { - throw new AwsException("DeleteConflict", - "Cannot delete instance profile with associated roles.", 409); + // Decided under the lock the attach path takes, so a role cannot be paired between the + // membership read and the delete; the profile's own monitor guards the read itself. + synchronized (resourceNameLock) { + InstanceProfile profile = getInstanceProfile(instanceProfileName); + List roleNames = profile.getRoleNames(); + synchronized (roleNames) { + if (!roleNames.isEmpty()) { + throw new AwsException("DeleteConflict", MUST_REMOVE_PROFILE_ROLES_FIRST, 409); + } + instanceProfiles.delete(instanceProfileName); + } } - instanceProfiles.delete(instanceProfileName); } public List listInstanceProfiles(String pathPrefix) { @@ -2972,39 +3091,52 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } public void addRoleToInstanceProfile(String instanceProfileName, String roleName) { - validateRoleName(roleName); - InstanceProfile profile = getInstanceProfile(instanceProfileName); - requireNotServiceLinked(getRole(roleName), roleName); - List roleNames = profile.getRoleNames(); - synchronized (roleNames) { - if (!roleNames.contains(roleName)) { - if (!roleNames.isEmpty()) { - // The quota name is what says which of the operation's limits fired, and it is - // this one rather than a roles-per-profile quota, which AWS publishes nowhere. - throw new AwsException("LimitExceeded", - "Cannot exceed quota for InstanceSessionsPerInstanceProfile: 1", 409); + // The lock DeleteRole and DeleteInstanceProfile decide under, taken outside the profile's + // own monitor as every path here does, so this cannot pair a role with a profile while + // either delete is between reading the pairing and acting on what it read. + synchronized (resourceNameLock) { + validateRoleName(roleName); + InstanceProfile profile = getInstanceProfile(instanceProfileName); + requireNotServiceLinked(getRole(roleName), roleName); + List roleNames = profile.getRoleNames(); + synchronized (roleNames) { + if (!roleNames.contains(roleName)) { + if (!roleNames.isEmpty()) { + // The quota name is what says which of the operation's limits fired, and + // it is this one rather than a roles-per-profile quota, which AWS + // publishes nowhere. + throw new AwsException("LimitExceeded", + "Cannot exceed quota for InstanceSessionsPerInstanceProfile: 1", 409); + } + roleNames.add(roleName); + instanceProfiles.put(instanceProfileName, profile); + indexPairing(instanceProfileName, roleName); } - roleNames.add(roleName); - instanceProfiles.put(instanceProfileName, profile); } } } public void removeRoleFromInstanceProfile(String instanceProfileName, String roleName) { - validateRoleName(roleName); - InstanceProfile profile = getInstanceProfile(instanceProfileName); - // Tolerates an already-deleted role that the profile still lists, so guard only what is - // still there; what the profile never held is a different case and AWS refuses it. - roles.get(roleName).ifPresent(role -> requireNotServiceLinked(role, roleName)); - List roleNames = profile.getRoleNames(); - // Whether the pairing is there and the removal of it are one decision, taken on the - // monitor the attach path holds, so a concurrent attach cannot land between them. - synchronized (roleNames) { - if (!roleNames.remove(roleName)) { - throw new AwsException("NoSuchEntity", "Role " + roleName + " in Instance Profile " - + instanceProfileName + " cannot be found.", 404); + // The lock the attach and the two deletes decide under, outside the profile's own monitor + // as they all take it: the pairing index is written here and read by DeleteRole, and both + // have to see the same thing the profile's own list says. + synchronized (resourceNameLock) { + validateRoleName(roleName); + InstanceProfile profile = getInstanceProfile(instanceProfileName); + // Tolerates an already-deleted role that the profile still lists, so guard only what + // is still there; what the profile never held is a different case and AWS refuses it. + roles.get(roleName).ifPresent(role -> requireNotServiceLinked(role, roleName)); + List roleNames = profile.getRoleNames(); + // Whether the pairing is there and the removal of it are one decision, taken on the + // monitor the attach path holds, so a concurrent attach cannot land between them. + synchronized (roleNames) { + if (!roleNames.remove(roleName)) { + throw new AwsException("NoSuchEntity", "Role " + roleName + " in Instance Profile " + + instanceProfileName + " cannot be found.", 404); + } + instanceProfiles.put(instanceProfileName, profile); + unindexPairing(instanceProfileName, roleName); } - instanceProfiles.put(instanceProfileName, profile); } } diff --git a/src/main/java/io/floci/aws/services/ssoadmin/SsoPermissionSetRoleProvisioner.java b/src/main/java/io/floci/aws/services/ssoadmin/SsoPermissionSetRoleProvisioner.java index a59ddb7af5..0b96fde1d0 100644 --- a/src/main/java/io/floci/aws/services/ssoadmin/SsoPermissionSetRoleProvisioner.java +++ b/src/main/java/io/floci/aws/services/ssoadmin/SsoPermissionSetRoleProvisioner.java @@ -135,6 +135,10 @@ public class SsoPermissionSetRoleProvisioner { RequestScopes.runAs(provisioning.accountId(), region, () -> { IamRole role = findRole(provisioning); if (role != null && ownsRole(provisioning, role)) { + // Asked before the policies go: a role an instance profile holds cannot be + // deleted, and emptying it first would leave the assignment's role in place + // with nothing on it. + iam.requireNotHeldByAnInstanceProfile(role.getRoleName()); iam.replaceRolePolicies(role.getRoleName(), role.getRoleId(), List.of(), Map.of(), null, 0); iam.deleteRole(role.getRoleName(), role.getRoleId()); } diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java index 94c8940baa..46768c727b 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java @@ -648,6 +648,33 @@ class IamRoleCfnProvisionerTest { order.verify(iam).deleteRole("app-role"); } + /** + * A role an instance profile still holds refuses the delete, and that refusal reaches the + * stack rather than being swallowed: AWS answers the same way, and taking a role out of a + * profile this stack may not own is not the provisioner's to do. It is asked before anything + * is cleared, so the role that stays keeps the policies it had rather than being emptied by a + * delete that could not finish. + */ + @Test + void deleteLetsAnInstanceProfileConflictReachTheStackWithNothingCleared() { + IamRole role = new IamRole("AROAheld-role", "held-role", "/", + "arn:aws:iam::" + ACCOUNT_ID + ":role/held-role", EMPTY_TRUST); + role.getAttachedPolicyArns().add("arn:aws:iam::aws:policy/ReadOnlyAccess"); + role.getInlinePolicies().put("bucket-read", EMPTY_TRUST); + when(iam.getRole("held-role")).thenReturn(role); + doThrow(new AwsException("DeleteConflict", + "Cannot delete entity, must remove roles from instance profile first.", 409)) + .when(iam).requireNotHeldByAnInstanceProfile("held-role"); + + AwsException refused = assertThrows(AwsException.class, + () -> provisioner.delete("AWS::IAM::Role", "held-role", "us-east-1")); + + assertEquals("DeleteConflict", refused.getErrorCode()); + verify(iam, never()).detachRolePolicy(anyString(), anyString()); + verify(iam, never()).deleteRolePolicy(anyString(), anyString()); + verify(iam, never()).deleteRole(anyString()); + } + @Test void deleteTreatsAnAlreadyMissingRoleAsDeleted() { when(iam.getRole("gone-role")).thenThrow(new AwsException("NoSuchEntity", "gone", 404)); diff --git a/src/test/java/io/floci/aws/services/iam/IamDeleteConflictDependencyIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamDeleteConflictDependencyIntegrationTest.java new file mode 100644 index 0000000000..6971ef7fab --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/IamDeleteConflictDependencyIntegrationTest.java @@ -0,0 +1,254 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.anyOf; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; + +/** + * Which dependency a blocked delete names, and in the sentence AWS was recorded answering. Three + * sentences cover the four refusals: an instance profile still holding the role, a managed policy + * that has to be detached, and an inline policy that has to be deleted. Each is entirely fixed + * text, so a caller reading it to pick its next step gets the dependency that is actually there. + * + *

{@code docs/services/iam.md} carries the recordings and says which part of the ordering is a + * reading rather than one of them. + */ +@QuarkusTest +class IamDeleteConflictDependencyIntegrationTest { + + private static final String IAM_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20261122/us-east-1/iam/aws4_request"; + + private static final String CODE = "ErrorResponse.Error.Code"; + private static final String MESSAGE = "ErrorResponse.Error.Message"; + + private static final String MUST_DETACH_POLICIES = + "Cannot delete entity, must detach all policies first."; + private static final String MUST_DELETE_POLICIES = + "Cannot delete entity, must delete policies first."; + private static final String MUST_REMOVE_PROFILE_ROLES = + "Cannot delete entity, must remove roles from instance profile first."; + + private static final String TRUST_POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":" + + "[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ec2.amazonaws.com\"}," + + "\"Action\":\"sts:AssumeRole\"}]}"; + + private static final String PERMISSION_POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":" + + "[{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + /** + * What a teardown step accepts. A test here may clear a dependency itself, to show the delete + * going through once it is gone, so a resource that is already absent is the step's work + * already done rather than a leak. Anything else, a refusal above all, still reports. + */ + private static void cleared(RequestSpecification request) { + request.when().post("/").then().statusCode(anyOf(is(200), is(404))); + } + + private static RequestSpecification iam(String action) { + return given().header("Authorization", IAM_AUTH).formParam("Action", action); + } + + private static String unique(String prefix) { + return prefix + "-" + Long.toString(System.nanoTime(), 36); + } + + private String createRole() { + String roleName = unique("conflict-role"); + iam("CreateRole").formParam("RoleName", roleName) + .formParam("AssumeRolePolicyDocument", TRUST_POLICY) + .when().post("/").then().statusCode(200); + cleanup.register(() -> cleared(iam("DeleteRole").formParam("RoleName", roleName))); + return roleName; + } + + private String createGroup() { + String groupName = unique("conflict-group"); + iam("CreateGroup").formParam("GroupName", groupName) + .when().post("/").then().statusCode(200); + cleanup.register(() -> cleared(iam("DeleteGroup").formParam("GroupName", groupName))); + return groupName; + } + + private String createUser() { + String userName = unique("conflict-user"); + iam("CreateUser").formParam("UserName", userName) + .when().post("/").then().statusCode(200); + cleanup.register(() -> cleared(iam("DeleteUser").formParam("UserName", userName))); + return userName; + } + + private String pairedProfile(String roleName) { + String profileName = unique("conflict-profile"); + iam("CreateInstanceProfile").formParam("InstanceProfileName", profileName) + .when().post("/").then().statusCode(200); + cleanup.register(() -> cleared(iam("DeleteInstanceProfile") + .formParam("InstanceProfileName", profileName))); + iam("AddRoleToInstanceProfile").formParam("InstanceProfileName", profileName) + .formParam("RoleName", roleName).when().post("/").then().statusCode(200); + cleanup.register(() -> cleared(iam("RemoveRoleFromInstanceProfile") + .formParam("InstanceProfileName", profileName).formParam("RoleName", roleName))); + return profileName; + } + + private String managedPolicy() { + String arn = iam("CreatePolicy").formParam("PolicyName", unique("conflict-policy")) + .formParam("PolicyDocument", PERMISSION_POLICY) + .when().post("/").then().statusCode(200) + .extract().xmlPath().getString("CreatePolicyResponse.CreatePolicyResult.Policy.Arn"); + cleanup.register(() -> cleared(iam("DeletePolicy").formParam("PolicyArn", arn))); + return arn; + } + + private String attachToRole(String roleName) { + return attach("AttachRolePolicy", "DetachRolePolicy", "RoleName", roleName); + } + + private String attachToGroup(String groupName) { + return attach("AttachGroupPolicy", "DetachGroupPolicy", "GroupName", groupName); + } + + /** Attaches a managed policy to the entity and hands back its ARN. */ + private String attach(String action, String undo, String param, String entityName) { + String arn = managedPolicy(); + iam(action).formParam(param, entityName).formParam("PolicyArn", arn) + .when().post("/").then().statusCode(200); + cleanup.register(() -> cleared( + iam(undo).formParam(param, entityName).formParam("PolicyArn", arn))); + return arn; + } + + private String inlineOnRole(String roleName) { + return putInline("PutRolePolicy", "DeleteRolePolicy", "RoleName", roleName); + } + + /** Embeds an inline policy in the entity and hands back its name. */ + private String putInline(String action, String undo, String param, String entityName) { + String policyName = unique("conflict-inline"); + iam(action).formParam(param, entityName).formParam("PolicyName", policyName) + .formParam("PolicyDocument", PERMISSION_POLICY) + .when().post("/").then().statusCode(200); + cleanup.register(() -> cleared(iam(undo).formParam(param, entityName) + .formParam("PolicyName", policyName))); + return policyName; + } + + /** The role an instance profile holds: the caller is told to take it out of the profile. */ + @Test + void aRoleAnInstanceProfileHoldsNamesTheProfile() { + String roleName = createRole(); + pairedProfile(roleName); + iam("DeleteRole").formParam("RoleName", roleName) + .when().post("/").then().statusCode(409) + .body(CODE, equalTo("DeleteConflict")) + .body(MESSAGE, equalTo(MUST_REMOVE_PROFILE_ROLES)); + } + + /** The profile holding it is refused with the same sentence, which is AWS's for both ends. */ + @Test + void theProfileHoldingARoleCarriesTheSameSentence() { + String profileName = pairedProfile(createRole()); + iam("DeleteInstanceProfile").formParam("InstanceProfileName", profileName) + .when().post("/").then().statusCode(409) + .body(CODE, equalTo("DeleteConflict")) + .body(MESSAGE, equalTo(MUST_REMOVE_PROFILE_ROLES)); + } + + /** + * Both dependencies at once: the profile is reported, which is the precedence AWS was recorded + * answering and the one a cleanup loop needs, since detaching the policy changes nothing here. + */ + @Test + void theProfileIsNamedAheadOfTheAttachedPolicy() { + String roleName = createRole(); + pairedProfile(roleName); + attachToRole(roleName); + iam("DeleteRole").formParam("RoleName", roleName) + .when().post("/").then().statusCode(409) + .body(MESSAGE, equalTo(MUST_REMOVE_PROFILE_ROLES)); + } + + /** A managed policy is detached, and the sentence says so. */ + @Test + void aRoleCarryingAManagedPolicyAsksForADetach() { + String roleName = createRole(); + attachToRole(roleName); + iam("DeleteRole").formParam("RoleName", roleName) + .when().post("/").then().statusCode(409) + .body(CODE, equalTo("DeleteConflict")) + .body(MESSAGE, equalTo(MUST_DETACH_POLICIES)); + } + + /** An inline policy is deleted rather than detached, and the sentence says that instead. */ + @Test + void aRoleCarryingAnInlinePolicyAsksForADelete() { + String roleName = createRole(); + inlineOnRole(roleName); + iam("DeleteRole").formParam("RoleName", roleName) + .when().post("/").then().statusCode(409) + .body(CODE, equalTo("DeleteConflict")) + .body(MESSAGE, equalTo(MUST_DELETE_POLICIES)); + } + + /** The group keeps the detach sentence for a managed policy, as the user already does. */ + @Test + void aGroupCarryingAManagedPolicyAsksForADetach() { + String groupName = createGroup(); + attachToGroup(groupName); + iam("DeleteGroup").formParam("GroupName", groupName) + .when().post("/").then().statusCode(409) + .body(CODE, equalTo("DeleteConflict")) + .body(MESSAGE, equalTo(MUST_DETACH_POLICIES)); + } + + /** The group's inline policy is a delete, the remedy that actually clears it. */ + @Test + void aGroupCarryingAnInlinePolicyAsksForADelete() { + String groupName = createGroup(); + putInline("PutGroupPolicy", "DeleteGroupPolicy", "GroupName", groupName); + iam("DeleteGroup").formParam("GroupName", groupName) + .when().post("/").then().statusCode(409) + .body(CODE, equalTo("DeleteConflict")) + .body(MESSAGE, equalTo(MUST_DELETE_POLICIES)); + } + + /** The user path is the model the other two follow, and it answers what it already did. */ + @Test + void aUserCarryingAnInlinePolicyStillAsksForADelete() { + String userName = createUser(); + putInline("PutUserPolicy", "DeleteUserPolicy", "UserName", userName); + iam("DeleteUser").formParam("UserName", userName) + .when().post("/").then().statusCode(409) + .body(CODE, equalTo("DeleteConflict")) + .body(MESSAGE, equalTo(MUST_DELETE_POLICIES)); + } + + /** The control: every dependency cleared in the order the refusals asked for, and it goes. */ + @Test + void theRoleGoesOnceEachDependencyNamedIsCleared() { + String roleName = createRole(); + String profileName = pairedProfile(roleName); + String policyArn = attachToRole(roleName); + String inlineName = inlineOnRole(roleName); + + iam("RemoveRoleFromInstanceProfile").formParam("InstanceProfileName", profileName) + .formParam("RoleName", roleName).when().post("/").then().statusCode(200); + iam("DeleteInstanceProfile").formParam("InstanceProfileName", profileName) + .when().post("/").then().statusCode(200); + iam("DetachRolePolicy").formParam("RoleName", roleName).formParam("PolicyArn", policyArn) + .when().post("/").then().statusCode(200); + iam("DeleteRolePolicy").formParam("RoleName", roleName).formParam("PolicyName", inlineName) + .when().post("/").then().statusCode(200); + iam("DeleteRole").formParam("RoleName", roleName).when().post("/").then().statusCode(200); + } +} diff --git a/src/test/java/io/floci/aws/services/iam/IamInstanceProfileRefusalIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamInstanceProfileRefusalIntegrationTest.java index 0f5ab41806..e618fbbb0d 100644 --- a/src/test/java/io/floci/aws/services/iam/IamInstanceProfileRefusalIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamInstanceProfileRefusalIntegrationTest.java @@ -13,8 +13,8 @@ import static org.hamcrest.Matchers.is; /** * What the instance profile pair refuses, in the sentences AWS was recorded answering: a second - * role names the quota that fired, and removing a role the profile never held is a 404 rather than - * a quiet success. + * role names the quota that fired, removing a role the profile never held is a 404 rather than a + * quiet success, and the role a profile holds goes only after the pairing does. * *

{@code docs/services/iam.md} carries the recordings. */ @@ -97,14 +97,16 @@ class IamInstanceProfileRefusalIntegrationTest { } /** - * A role deleted while the profile still lists it stays removable, which is the case the - * tolerance was there for and is not the one AWS refuses. The role goes first and the pairing - * after it, so the removal is the one that reaches a profile listing a role that is not there. + * The pairing goes before the role does, which is what puts the state the removal tolerates + * (a profile listing a role that is no longer there) out of reach of anything served: the + * delete is refused while the profile holds the role, and succeeds once it does not. The + * tolerance stays for state reached another way, and the sentence the refusal carries is + * covered with the other three in {@link IamDeleteConflictDependencyIntegrationTest}. */ @Test - void aRoleDeletedWhileStillListedStaysRemovable() { + void theRoleAProfileHoldsGoesOnlyAfterThePairing() { String profileName = createProfile(); - String roleName = unique("profile-ghost-role"); + String roleName = unique("profile-paired-role"); iam("CreateRole").formParam("RoleName", roleName) .formParam("AssumeRolePolicyDocument", TRUST_POLICY) .when().post("/").then().statusCode(200); @@ -116,9 +118,11 @@ class IamInstanceProfileRefusalIntegrationTest { .formParam("InstanceProfileName", profileName) .formParam("RoleName", roleName) .when().post("/").then().statusCode(anyOf(is(200), is(404)))); - iam("DeleteRole").formParam("RoleName", roleName).when().post("/").then().statusCode(200); + iam("DeleteRole").formParam("RoleName", roleName).when().post("/").then().statusCode(409) + .body(CODE, equalTo("DeleteConflict")); iam("RemoveRoleFromInstanceProfile").formParam("InstanceProfileName", profileName) .formParam("RoleName", roleName).when().post("/").then().statusCode(200); + iam("DeleteRole").formParam("RoleName", roleName).when().post("/").then().statusCode(200); } /** The control: the first role still attaches, and removing it still succeeds. */ diff --git a/src/test/java/io/floci/aws/services/iam/IamServiceTest.java b/src/test/java/io/floci/aws/services/iam/IamServiceTest.java index d4d0602881..ba5b20119a 100644 --- a/src/test/java/io/floci/aws/services/iam/IamServiceTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamServiceTest.java @@ -2939,6 +2939,59 @@ class IamServiceTest { assertEquals("P1", profiles.getFirst().getInstanceProfileName()); } + /** + * A role delete asks which profiles hold the role rather than reading every profile in the + * account, so clearing out many roles while many profiles are about costs one lookup each and + * still refuses exactly the role that is paired. + */ + @Test + void deletingManyRolesWithManyProfilesRefusesOnlyThePairedOne() { + for (int i = 0; i < 40; i++) { + iamService.createInstanceProfile("BulkProfile" + i, "/"); + iamService.createRole("BulkRole" + i, "/", EMPTY_POLICY_DOCUMENT, null, 0, null); + } + iamService.addRoleToInstanceProfile("BulkProfile7", "BulkRole7"); + + for (int i = 0; i < 40; i++) { + if (i != 7) { + iamService.deleteRole("BulkRole" + i); + } + } + assertEquals("DeleteConflict", assertThrows(AwsException.class, + () -> iamService.deleteRole("BulkRole7")).getErrorCode()); + + iamService.removeRoleFromInstanceProfile("BulkProfile7", "BulkRole7"); + iamService.deleteRole("BulkRole7"); + } + + /** + * A pairing the store already carried is seen by a service that did not write it: the lookup + * is filled from the profiles it finds, so a restart does not make a held role deletable. + */ + @Test + void aPairingAlreadyInStorageStillBlocksTheDelete() { + StorageBackend roles = new InMemoryStorage<>(); + StorageBackend profiles = new InMemoryStorage<>(); + IamService before = iamServiceOn(roles, profiles); + before.createRole("CarriedRole", "/", EMPTY_POLICY_DOCUMENT, null, 0, null); + before.createInstanceProfile("CarriedProfile", "/"); + before.addRoleToInstanceProfile("CarriedProfile", "CarriedRole"); + + IamService after = iamServiceOn(roles, profiles); + + assertEquals("DeleteConflict", assertThrows(AwsException.class, + () -> after.deleteRole("CarriedRole")).getErrorCode()); + after.removeRoleFromInstanceProfile("CarriedProfile", "CarriedRole"); + after.deleteRole("CarriedRole"); + } + + private static IamService iamServiceOn(StorageBackend roles, + StorageBackend instanceProfiles) { + return new IamService(new InMemoryStorage<>(), new InMemoryStorage<>(), roles, new InMemoryStorage<>(), + new InMemoryStorage<>(), instanceProfiles, new InMemoryStorage<>(), + new RegionResolver("us-east-1", "000000000000"), false); + } + // ========================================================================= // AWS Managed Policy Seeding // ========================================================================= diff --git a/src/test/java/io/floci/aws/services/ssoadmin/SsoPermissionSetRoleProvisionerTest.java b/src/test/java/io/floci/aws/services/ssoadmin/SsoPermissionSetRoleProvisionerTest.java index 42c2bbd4f7..940a19a846 100644 --- a/src/test/java/io/floci/aws/services/ssoadmin/SsoPermissionSetRoleProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/ssoadmin/SsoPermissionSetRoleProvisionerTest.java @@ -28,6 +28,7 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -109,6 +110,27 @@ class SsoPermissionSetRoleProvisionerTest { assertEquals(List.of(cleanupFailure), List.of(thrown.getSuppressed())); } + /** + * Removing an assignment empties the role before deleting it, so a role an instance profile + * holds has to be refused before that: otherwise the delete it cannot finish would leave the + * assignment's role in place with nothing on it. + */ + @Test + void anAssignmentWhoseRoleAProfileHoldsKeepsItsPolicies() { + PermissionSetProvisioning provisioning = new PermissionSetProvisioning("permission-set", ACCOUNT, STATUS, + ARN, "role-id"); + when(iam.findRole(ACCOUNT, NAME)).thenReturn(Optional.of(new IamRole("role-id", NAME, PATH, ARN, "{}"))); + doThrow(new AwsException("DeleteConflict", + "Cannot delete entity, must remove roles from instance profile first.", 409)) + .when(iam).requireNotHeldByAnInstanceProfile(NAME); + + assertEquals("DeleteConflict", assertThrows(AwsException.class, + () -> provisioner.remove(provisioning, "us-east-1")).getErrorCode()); + + verify(iam, never()).replaceRolePolicies(anyString(), anyString(), any(), any(), any(), anyInt()); + verify(iam, never()).deleteRole(anyString(), anyString()); + } + @Test void provisioningJsonPreservesRoleIdentityAndAcceptsLegacyRecords() throws Exception { ObjectMapper mapper = new ObjectMapper(); diff --git a/src/test/java/io/floci/aws/testing/EnforcementFixtures.java b/src/test/java/io/floci/aws/testing/EnforcementFixtures.java index 772263f0ab..8f7aab5468 100644 --- a/src/test/java/io/floci/aws/testing/EnforcementFixtures.java +++ b/src/test/java/io/floci/aws/testing/EnforcementFixtures.java @@ -278,14 +278,23 @@ public final class EnforcementFixtures { } /** - * Deletes a role, and first the policies it carries: Floci answers {@code DeleteConflict}, - * "must detach all policies first", for a role holding either an inline or a managed one. + * Deletes a role, and first what IAM wants gone before it will: any instance profile holding + * it, then its managed attachments and its inline policies. Each of those is refused with its + * own {@code DeleteConflict} sentence, and the profile is reported ahead of the policies, so a + * teardown that left one in place would be told to remedy something else. */ public static void removeRole(int port, String authorization, String roleName) { if (iam(port, authorization, "GetRole", "RoleName", roleName) .extract().statusCode() == 404) { return; } + for (String profileName : iam(port, authorization, "ListInstanceProfilesForRole", + "RoleName", roleName).statusCode(200).extract().xmlPath() + .getList("ListInstanceProfilesForRoleResponse.ListInstanceProfilesForRoleResult" + + ".InstanceProfiles.member.InstanceProfileName", String.class)) { + iam(port, authorization, "RemoveRoleFromInstanceProfile", + "InstanceProfileName", profileName, "RoleName", roleName).statusCode(200); + } for (String policyName : iam(port, authorization, "ListRolePolicies", "RoleName", roleName) .statusCode(200).extract().xmlPath() .getList("ListRolePoliciesResponse.ListRolePoliciesResult.PolicyNames.member",